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

1 Answer

0 votes
object ReplaceLastOccurrence {
  def replaceLastOccurrence(s: String, oldsub: String, newsub: String): String = {
    val lastIndex = s.lastIndexOf(oldsub)
    
    if (lastIndex == -1) 
      s
    else 
      s.substring(0, lastIndex) + newsub + s.substring(lastIndex + oldsub.length)
  }

  def main(args: Array[String]): Unit = {
    val s = "Scala programming lets you write less to do more programming"
    
    val oldsub = "programming"
    val newsub = "ABC"
    
    val result = replaceLastOccurrence(s, oldsub, newsub)
    
    println(result) 
  }
}

 
 
/*
run:
   
Scala programming lets you write less to do more ABC
 
*/

 



answered Dec 28, 2024 by avibootz
edited Dec 28, 2024 by avibootz
...