英文:
How to split string in GO by array of runes?
问题
如果你有一个由符文数组作为分隔符的字符串,有没有办法将它拆分成字符串数组?以下是我想要的一个示例:
separators = {' ',')','('}
SomeFunction("my string(qq bb)zz",separators) => {"my","string","qq","bb","zz"}
英文:
If there is any way to split string into array of strings, when you have as a separator an array of runes? There is an example what I want:
seperators = {' ',')','('}
SomeFunction("my string(qq bb)zz",seperators) => {"my","string","qq","bb","zz"}
答案1
得分: 13
例如,
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"]
英文:
For example,
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)
}
Output:
"my string(qq bb)zz"
["my" "string" "qq" "bb" "zz"]
答案2
得分: 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"]
英文:
with regexp:
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)
}
output:
"my string(qq bb)zz"
["my" "string" "qq" "bb" "zz"]
答案3
得分: 0
我相信一个更简单的方法是使用函数FieldsFunc。以下是它的实现示例:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := func(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
fmt.Printf("Fields are: %q", strings.FieldsFunc(" foo1;bar2,baz3...", f))
}
输出结果:
Fields are: ["foo1" "bar2" "baz3"]
英文:
I believe that a simpler approach would be to use the function FieldsFunc. Here is an example of it's implementation:
package main
import (
"fmt"
"strings"
"unicode"
)
func main() {
f := func(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}
fmt.Printf("Fields are: %q", strings.FieldsFunc(" foo1;bar2,baz3...", f))
}
Output :
> Fields are: ["foo1" "bar2" "baz3"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论