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

报告相同问题?

悬赏问题

  • ¥20 有没有会写mysql的,有偿做个问题
  • ¥20 win11账户锁定时间设为0无法登录
  • ¥45 C#学生成绩管理系统
  • ¥15 VB.NET2022如何生成发布成exe文件
  • ¥30 matlab appdesigner私有函数嵌套整合
  • ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?