英文:
Loop repeated data ini a string with Golang
问题
我有一个像这样的字符串
xx5645645yyxx9879869yyxx3879870977yy
想要通过循环得到以下结果
xx5645645yy
xx9879869yy
xx3879870977yy
我不知道如何做,请帮忙,非常感谢。
英文:
I have a string like this
xx5645645yyxx9879869yyxx3879870977yy
Want to get result like following with loop
xx5645645yy
xx9879869yy
xx3879870977yy
I have no idea to do it, any kind of help is greatly appreciated, thanks
答案1
得分: 1
你可以使用strings.Split()函数并在"xx"上进行分割,然后在循环中将"xx"重新添加到每个分割的子字符串之前:
package main
import (
"fmt"
"strings"
)
func main() {
s := "xx5645645yyxx9879869yyxx3879870977yy"
items := strings.Split(s, "xx")[1:] // [1:] 跳过第一个空项
for _, item := range items {
fmt.Println("xx" + item)
}
}
这将产生以下结果:
xx5645645yy
xx9879869yy
xx3879870977yy
英文:
You can use the strings.Split() function and split on "xx", then prepend "xx" back to each of the split substrings in the loop:
package main
import (
"fmt"
"strings"
)
func main() {
s := "xx5645645yyxx9879869yyxx3879870977yy"
items := strings.Split(s, "xx")[1:] // [1:] to skip the first, empty, item
for _, item := range items {
fmt.Println("xx" + item)
}
}
Which produces:
xx5645645yy
xx9879869yy
xx3879870977yy
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论