How to split Golang strings without deleting separator?

前端 未结 3 1793
南笙
南笙 2021-01-15 08:55

According to the answer at How to split a string and assign it to variables in Golang? splitting a string results in an array of strings where the separator is not present i

相关标签:
3条回答
  • 2021-01-15 09:27

    Try this to get the proper result.

    package main
    
        import (
            "fmt"
            "strings"
        )
    
        func main() {
            str := "Potato:Salad:Popcorn:Cheese"
            a := strings.SplitAfter(str, ":")
            for i := 0; i < len(a); i++ {
                fmt.Println(a[i])
            }
        }
    
    0 讨论(0)
  • 2021-01-15 09:32

    The answer above by daplho great and simple. Sometimes I just like to provide an alternative to remove the magic of a function

    package main
    
    import "fmt"
    
    var s = "Potato:Salad:Popcorn:Cheese"
    
    func main() {
        a := split(s, ':')
        fmt.Println(a)
    }
    
    func split(s string, sep rune) []string {
        var a []string
        var j int
        for i, r := range s {
            if r == sep {
                a = append(a, s[j:i+1])
                j = i + 1
            }
        }
        a = append(a, s[j:])
        return a
    }
    

    https://goplay.space/#h9sDd1gjjZw

    As a side note, the standard lib version is better than the hasty one above

    goos: darwin
    goarch: amd64
    BenchmarkSplit-4             5000000           339 ns/op
    BenchmarkSplitAfter-4       10000000           143 ns/op
    

    So go with that lol

    0 讨论(0)
  • 2021-01-15 09:34

    You are looking for SplitAfter.

    s := strings.SplitAfter("Potato:Salad:Popcorn:Cheese", ":")
      for _, element := range s {
      fmt.Println(element)
    }
    // Potato:
    // Salad:
    // Popcorn:
    // Cheese
    

    Go Playground

    0 讨论(0)
提交回复
热议问题