【发布时间】: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
我知道理论上我可以将“:”附加到每个元素的末尾,除了最后一个,但如果可能的话,我正在寻找一个更通用、更优雅的解决方案。
【问题讨论】:
-
可以尝试搜索
:,通过索引获取子字符串,不用split()方法。