How to replace the last occurrence of a substring in a string with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

func replaceLastOccurrence(s, oldsub, newsub string) string {
    index := strings.LastIndex(s, oldsub)
    
    if index == -1 {
        return s
    }
    
    return s[:index] + newsub + s[index + len(oldsub):]
}

func main() {
    s := "Go programming statically typed programming compiled high-level programming"
    
    oldSubstring := "programming"
    newSubstring := "ABC"
    
    result := replaceLastOccurrence(s, oldSubstring, newSubstring)
    
    fmt.Println(result)
}


     
/*
run:
  
Go programming statically typed programming compiled high-level ABC
  
*/

 



answered Dec 28, 2024 by avibootz
...