上QQ阅读APP看书,第一时间看更新
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 (
"fmt"
"strings"
)
const refString = "Mary_had a little_lamb"
func main() {
words := strings.Split(refString, "_")
for idx, word := range words {
fmt.Printf("Word %d is: %s\n", idx, word)
}
}
- Run the code by executing go run anyother.go.
- See the output in the Terminal:
- Create another file called specfunction.go with the following content:
package main
import (
"fmt"
"strings"
)
const refString = "Mary*had,a%little_lamb"
func main() {
// The splitFunc is called for each
// rune in a string. If the rune
// equals any of character in a "*%,_"
// the refString is split.
splitFunc := func(r rune) bool {
return strings.ContainsRune("*%,_", r)
}
words := strings.FieldsFunc(refString, splitFunc)
for idx, word := range words {
fmt.Printf("Word %d is: %s\n", idx, word)
}
}
- Run the code by executing go run specfunction.go.
- See the output in the Terminal:
- Create another file called regex.go with the following content:
package main
import (
"fmt"
"regexp"
)
const refString = "Mary*had,a%little_lamb"
func main() {
words := regexp.MustCompile("[*,%_]{1}").Split(refString, -1)
for idx, word := range words {
fmt.Printf("Word %d is: %s\n", idx, word)
}
}
- Run the code by executing go run regex.go.
- See the output in the Terminal: