Home > Blockchain >  Loop repeated data ini a string with Golang
Loop repeated data ini a string with Golang

Time:10-06

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

CodePudding user response:

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
  •  Tags:  
  • go
  • Related