Breaking the string into words
Breaking the string into words could be tricky. First, decide what the word is, as well as what the separator is, and if there is any whitespace or any other characters. After these decisions have been made, you can choose the appropriate function from the strings
package. This recipe will describe common cases.
How to do it...
- Open the console and create the folder
chapter02/recipe02
. - Navigate to the directory.
- Create the
whitespace.go
file with the following content:
package main import ( "fmt" "strings" ) const refString = "Mary had a little lamb" func main() { words := strings.Fields(refString) for idx, word := range words { fmt.Printf("Word %d is: %s\n", idx, word) } }
- Run the code by executing
go run whitespace.go
. - See the output in the Terminal:

- Create another file called
anyother.go
with the following content:
package main import...