5

It is my second day with golang, I'll probably ask a very basic question:

I want to replace parts of a string, that is what strings.Replace is good for:

func Replace(s, old, new string, n int) string

The last parameter is the number of times old gets replaced by new - starting from the beginning of the string.

Is there a similar standard function that starts from the end?

linqu
  • 11,320
  • 8
  • 55
  • 67

1 Answers1

4

There is no such standard function you seek for.

Alternative #1: with Reverse

Using a string-reverse function (taken from here):

func Rev(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

Your solution is:

Rev(strings.Replace(Rev(s), Rev(old), Rev(new), n))

Alternative #2: do-it-yourself

You can simply use a for and strings.LastIndex() to find replacable substrings and replace them.

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827