dongzheng3113 2018-08-15 01:03
浏览 69
已采纳

如何在不删除分隔符的情况下分割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条回答 默认 最新

  • dongqiang4986 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效