英文:
How to split the string in such way?
问题
我需要将类似于"aa bb cc dd ee ff"的字符串在Golang中拆分为:
["aa bb" "bb cc" "cc dd" "dd ee" "ee ff"]
我尝试了以下代码:
re := regexp.MustCompile("[a-z]+\s+[a-z]+")
fmt.Printf("%q\n", re.FindAllString("aa bb cc dd ee ff", -1))
但是它返回的结果是:
["aa bb" "cc dd" "ee ff"]
英文:
I need to split a string like "aa bb cc dd ee ff" in golang to
["aa bb" "bb cc" "cc dd" "dd ee" "ee ff"]
I'm trying this:
re := regexp.MustCompile("[a-z]+\\s+[a-z]+")
fmt.Printf("%q\n", re.FindAllString("aa bb cc dd ee ff", -1))
But it returns:
["aa bb" "cc dd" "ee ff"]
答案1
得分: 2
例如,
package main
import (
"fmt"
"strings"
)
func pairs(s string) []string {
var p []string
fs := strings.Fields(s)
if len(fs) >= 2 {
p = make([]string, 0, len(fs)-1)
for i, f := range fs[1:len(fs)] {
p = append(p, fs[i]+" "+f)
}
}
return p
}
func main() {
s := "aa bb cc dd ee ff"
fmt.Printf("%q\n", s)
p := pairs(s)
fmt.Printf("%q\n", p)
}
输出:
"aa bb cc dd ee ff"
["aa bb" "bb cc" "cc dd" "dd ee" "ee ff"]
英文:
For example,
package main
import (
"fmt"
"strings"
)
func pairs(s string) []string {
var p []string
fs := strings.Fields(s)
if len(fs) >= 2 {
p = make([]string, 0, len(fs)-1)
for i, f := range fs[1:len(fs)] {
p = append(p, fs[i]+" "+f)
}
}
return p
}
func main() {
s := "aa bb cc dd ee ff"
fmt.Printf("%q\n", s)
p := pairs(s)
fmt.Printf("%q\n", p)
}
Output:
"aa bb cc dd ee ff"
["aa bb" "bb cc" "cc dd" "dd ee" "ee ff"]
答案2
得分: 0
你忘了说这是一个重复模式:
([a-z]+\\s+[a-z]+)*
解决方案((?=([a-z]{2}\s+[a-z]{2})*)
)需要使用前瞻,但是Go语言中不可用。
英文:
<strike>
You forget to say that it's a repeating pattern:
([a-z]+\\s+[a-z]+)*
</strike>
The solution ((?=([a-z]{2}\s+[a-z]{2})*)
) needs lookahead which is not available in go
答案3
得分: 0
你可以使用bufio.Scanner
进行迭代:
package main
import (
"bufio"
"strings"
)
func abc(data []byte, eof bool) (int, []byte, error) {
if eof {
return 0, nil, nil
}
a := -1
for b, c := range data {
if c == ' ' {
if a >= 0 {
return a+1, data[:b], nil
}
a = b
}
}
return len(data), data, nil
}
func main() {
s := bufio.NewScanner(strings.NewReader("aa bb cc dd ee ff"))
s.Split(abc)
for s.Scan() {
println(s.Text())
}
}
https://golang.org/pkg/bufio#Scanner.Split
英文:
You can iterate with a bufio.Scanner
:
package main
import (
"bufio"
"strings"
)
func abc(data []byte, eof bool) (int, []byte, error) {
if eof {
return 0, nil, nil
}
a := -1
for b, c := range data {
if c == ' ' {
if a >= 0 {
return a+1, data[:b], nil
}
a = b
}
}
return len(data), data, nil
}
func main() {
s := bufio.NewScanner(strings.NewReader("aa bb cc dd ee ff"))
s.Split(abc)
for s.Scan() {
println(s.Text())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论