如何在不删除分隔符的情况下分割Golang字符串? [英] How to split Golang strings without deleting separator?

查看:100
本文介绍了如何在不删除分隔符的情况下分割Golang字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据中的答案如何在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)
}

输出:

Potato
Salad
Popcorn
Cheese

我希望输出以下内容:

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.

推荐答案

您正在寻找 SplitAfter .

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

去操场

这篇关于如何在不删除分隔符的情况下分割Golang字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆