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

根据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

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


幕布斯6054654
浏览 87回答 3
3回答

犯罪嫌疑人X

您正在寻找SplitAfter。s := strings.SplitAfter("Potato:Salad:Popcorn:Cheese", ":")  for _, element := range s {  fmt.Println(element)}// Potato:// Salad:// Popcorn:// Cheese

交互式爱情

daplho 上面的答案非常简单。有时我只是想提供一种替代方法来消除函数的魔力package mainimport "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: darwingoarch: amd64BenchmarkSplit-4             5000000           339 ns/opBenchmarkSplitAfter-4       10000000           143 ns/op所以跟那个大声笑

动漫人物

试试这个以获得正确的结果。package main&nbsp; &nbsp; import (&nbsp; &nbsp; &nbsp; &nbsp; "fmt"&nbsp; &nbsp; &nbsp; &nbsp; "strings"&nbsp; &nbsp; )&nbsp; &nbsp; func main() {&nbsp; &nbsp; &nbsp; &nbsp; str := "Potato:Salad:Popcorn:Cheese"&nbsp; &nbsp; &nbsp; &nbsp; a := strings.SplitAfter(str, ":")&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < len(a); i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(a[i])&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP