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

报告相同问题?