如果有任何方法将字符串拆分为字符串数组,那么当你将符号作为符号数组时?有一个我想要的例子:
seperators = {' ',')','('}
SomeFunction("my string(qq bb)zz",seperators) => {"my","string","qq","bb","zz"}
答案 0 :(得分:10)
例如,
package main
import (
"fmt"
"strings"
)
func split(s string, separators []rune) []string {
f := func(r rune) bool {
for _, s := range separators {
if r == s {
return true
}
}
return false
}
return strings.FieldsFunc(s, f)
}
func main() {
separators := []rune{' ', ')', '('}
s := "my string(qq bb)zz"
ss := split(s, separators)
fmt.Printf("%q\n", s)
fmt.Printf("%q\n", ss)
}
输出:
"my string(qq bb)zz"
["my" "string" "qq" "bb" "zz"]
答案 1 :(得分:2)
使用正则表达式:
package main
import (
"fmt"
"regexp"
)
var re = regexp.MustCompile("[() ]")
func main() {
text := "my string(qq bb)zz"
splinedText := re.Split(text, -1)
fmt.Printf("%q\n", text)
fmt.Printf("%q\n", splinedText)
}
输出:
"my string(qq bb)zz"
["my" "string" "qq" "bb" "zz"]