dtqi87613
2018-08-15 01:03
浏览 228
已采纳

如何在不删除分隔符的情况下分割Golang字符串?

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 in any of the strings in the array. Is there a way to split strings such that the separator is on the last line of a given string?

e.x.

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

outputs:

Potato
Salad
Popcorn
Cheese

I wish to output the following instead:

Potato:
Salad:
Popcorn:
Cheese

I know I could theoretically append ":" to the end of each element except for the last, but I'm looking for a more general, elegant solution if possible.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doumu2172 2018-08-15 02:05
    已采纳

    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

    打赏 评论
  • dongtong2021 2018-08-16 03:03

    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

    打赏 评论
  • dongyata3336 2019-06-01 18:18

    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])
            }
        }
    
    打赏 评论

相关推荐 更多相似问题