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

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

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

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:

确定