Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Scala program that replaces multiple strings with their corresponding replacement strings in Scala.
We can achieve this in an elegant way using the foldLeft() function.
Let’s look at the program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.practice object StringReplacer extends App { val inputStr = """ |Hi, I love fruits. |I like Apples and Oranges. |""".stripMargin val replaceStrMap: Map[String, String] = Map( "Hi" -> "Hello", "I" -> "We", "Apples" -> "Bananas", "Oranges" -> "Kiwi" ) val replacedStr = replaceStrMap.foldLeft(inputStr)((acc, pair) => acc.replace(pair._1, pair._2)) println(s"==== input string ==== $inputStr") println(s"==== replaced string ==== $replacedStr") } |
Output:
Happy learning.
Please leave a reply in case of any queries.