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

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证