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?
There is no such standard function you seek for.
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))
You can simply use a for
and strings.LastIndex()
to find replacable substrings and replace them.