【问题标题】:How to split Golang strings without deleting separator?如何在不删除分隔符的情况下拆分 Golang 字符串?
【发布时间】:2019-01-21 21:52:33
【问题描述】:

根据How to split a string and assign it to variables in Golang? 的答案,拆分字符串会产生一个字符串数组,其中分隔符不存在于数组中的任何字符串中。有没有办法拆分字符串,使分隔符位于给定字符串的最后一行?

例如

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

输出:

Potato
Salad
Popcorn
Cheese

我希望输出以下内容:

Potato:
Salad:
Popcorn:
Cheese

我知道理论上我可以将“:”附加到每个元素的末尾,除了最后一个,但如果可能的话,我正在寻找一个更通用、更优雅的解决方案。

【问题讨论】:

标签: string go split


【解决方案1】:

您正在寻找SplitAfter

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

Go Playground

【讨论】:

    【解决方案2】:

    daplho 上面的答案非常简单。有时我只是想提供一种替代方法来消除函数的魔力

    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

    顺便说一句,标准的lib版本比上面草率的要好

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

    那就去吧,哈哈

    【讨论】:

    【解决方案3】:

    试试这个以获得正确的结果

    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])
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2013-05-10
      • 1970-01-01
      • 2020-04-09
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      相关资源
      最近更新 更多