我开始学习Go,我想实现一些算法。
我想迭代一个字符串,然后提取一些子字符串,例如:p -(40) *(GOT) +(FF)
应返回如下数组:[p, 40, GOT, FF]
我写了这样的东西,但它含糊不清:
import (
"strings"
)
func find(input string){
var result []string
a := strings.SplitN(input, "-(", 2);
result[0] = a[0]
b := strings.SplitN(a[1], ") *(", 2)
result[1] = b[0]
c := strings.SplitN(a[1], ") +(", 2)
result[2] = c[0]
d := strings.SplitN(a[1], ")", 2)
result[3] = d[0]
}
有人可以纠正我或建议更容易吗?谢谢!
答案 0 :(得分:1)
您可以使用strings.FieldsFunc
,例如此工作示例代码:
package main
import "fmt"
import "strings"
func find(input string) []string {
return strings.FieldsFunc(input, split)
}
func main() {
strs := find("p -(40) *(GOT) +(FF)")
str := strings.Replace(fmt.Sprint(strs), " ", ", ", -1)
fmt.Println(str)
}
func split(r rune) bool {
return r == ' ' || r == '-' || r == '(' || r == ')' || r == '*' || r == '+'
}
输出:
[p, 40, GOT, FF]
您可以使用strings.Fields
然后strings.Trim
,就像这个工作示例代码:
package main
import "fmt"
import "strings"
func main() {
fmt.Println(find("p -(40) *(GOT) +(FF)"))
}
func find(input string) []string {
strs := strings.Fields(input)
result := make([]string, 0, len(strs))
for _, v := range strs {
s := strings.Trim(v, "()+-*")
if len(s) > 0 {
result = append(result, s)
}
}
return result
}
输出:
[p 40 GOT FF]
这也适用于您的特殊情况:
package main
import "fmt"
import "strings"
func main() {
fmt.Println(find("p -(40) *(GOT) +(FF)"))
}
func find(input string) []string {
strs := strings.Fields(input)
for i := 0; i < len(strs); i++ {
strs[i] = strings.Trim(strs[i], "()+-*")
}
return strs
}
输出:
[p 40 GOT FF]
如果你需要像这个字符串[p, 40, GOT, FF]
这样的输出,试试这个工作示例代码:
package main
import "fmt"
import "strings"
func main() {
strs := find("p -(40) *(GOT) +(FF)")
str := strings.Replace(fmt.Sprint(strs), " ", ", ", -1)
fmt.Println(str)
}
func find(input string) []string {
strs := strings.Fields(input)
for i := 0; i < len(strs); i++ {
strs[i] = strings.Trim(strs[i], "()+-*")
}
return strs
}
输出:
[p, 40, GOT, FF]