Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Open the console and create the folder chapter02/recipe02.
  2. Navigate to the directory.
  3. 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)
}

}
  1. Run the code by executing go run whitespace.go.
  2. See the output in the Terminal:
  1. 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)
}

}
  1. Run the code by executing go run anyother.go.
  2. See the output in the Terminal:
  1. 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)
}

}
  1. Run the code by executing go run specfunction.go.
  2. See the output in the Terminal:
  1. 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)
}

}
  1. Run the code by executing go run regex.go.
  2. See the output in the Terminal: