dongtu7567 2015-10-23 19:37
浏览 142
已采纳

从string.Replace()Golang反向返回

I have a large dataset where I needed to do some string manipulation (I know strings are immutable). The Replace() function in the strings package does exactly what I need, except I need it to search in reverse.

Say I have this string: AA-BB-CC-DD-EE

Run this script:

package main

import (
"fmt"
"strings"
)

func main() {
    fmt.Println(strings.Replace("AA-BB-CC-DD-EE", "-", "", 1))
}

It outputs: AABB-CC-DD-EE

What I need is: AA-BBCCDDEE, where the first instance of the search key is found, and the rest discarded.

Splitting the string, inserting the dash, and joining it back together works. But, I'm thinking there is a more performant way to achieve this.

  • 写回答

4条回答 默认 最新

  • duanpei4455 2015-10-24 06:05
    关注

    String slices!

    in := "AA-BB-CC-DD-EE"
    afterDash := strings.Index(in, "-") + 1
    fmt.Println(in[:afterDash] + strings.Replace(in[afterDash:], "-", "", -1))
    

    (might require some tweaking to get the behavior you want in the case that the input has no dashes).

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

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案