Replace Nth occurrence of string in golang

Viewed 7989

How do I replace the nth (in this case second) occurrence of a string in golang? The following code replaces the example string optimismo from optimism with o from optimism when I want it to be optimismo from

package main

import (
    "fmt"
    "strings"
)

func main() {
    mystring := "optimismo from optimism"
    excludingSecond := strings.Replace(mystring, "optimism", "", 1)
    fmt.Println(excludingSecond)
}
3 Answers

For anyone stumbling on this post and is looking to replace the LAST occurrence

package main

import (
    "fmt"
    "strings"
)

func main() {
    mystring := "optimismo from optimism"

    i := strings.LastIndex(mystring, "optimism")
    excludingLast := mystring[:i] + strings.Replace(mystring[i:], "optimism", "", 1)
    fmt.Println(excludingLast)
}
Related