遍历带空格的字符串
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
", idx, word)
}
}
/*
Word 0 is: Mary
Word 1 is: had
Word 2 is: a
Word 3 is: little
Word 4 is: lamb
*/
指定分割的字符串
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
", idx, word)
}
}
/*
Word 0 is: Mary
Word 1 is: had a little
Word 2 is: lamb
*/
去除特别符号
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 splitted.
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
", idx, word)
}
}
/*
Word 0 is: Mary
Word 1 is: had
Word 2 is: a
Word 3 is: little
Word 4 is: lamb
*/
正则去掉特别字符串
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
", idx, word)
}
}
/*
Word 0 is: Mary
Word 1 is: had
Word 2 is: a
Word 3 is: little
Word 4 is: lamb
*/