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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?