使用Golang在字符串中重复循环数据。

huangapple go评论104阅读模式
英文:

Loop repeated data ini a string with Golang

问题

我有一个像这样的字符串

  1. xx5645645yyxx9879869yyxx3879870977yy

想要通过循环得到以下结果

  1. xx5645645yy
  2. xx9879869yy
  3. xx3879870977yy

我不知道如何做,请帮忙,非常感谢。

英文:

I have a string like this

  1. xx5645645yyxx9879869yyxx3879870977yy

Want to get result like following with loop

  1. xx5645645yy
  2. xx9879869yy
  3. xx3879870977yy

I have no idea to do it, any kind of help is greatly appreciated, thanks

答案1

得分: 1

你可以使用strings.Split()函数并在"xx"上进行分割,然后在循环中将"xx"重新添加到每个分割的子字符串之前:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. s := "xx5645645yyxx9879869yyxx3879870977yy"
  8. items := strings.Split(s, "xx")[1:] // [1:] 跳过第一个空项
  9. for _, item := range items {
  10. fmt.Println("xx" + item)
  11. }
  12. }

这将产生以下结果:

  1. xx5645645yy
  2. xx9879869yy
  3. 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:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. s := "xx5645645yyxx9879869yyxx3879870977yy"
  8. items := strings.Split(s, "xx")[1:] // [1:] to skip the first, empty, item
  9. for _, item := range items {
  10. fmt.Println("xx" + item)
  11. }
  12. }

Which produces:

  1. xx5645645yy
  2. xx9879869yy
  3. xx3879870977yy

huangapple
  • 本文由 发表于 2022年10月6日 12:51:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/73968790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定