Scala program to replace all occurrences of a substring

1. Introduction

Replacing substrings within a string is a common task in programming and text processing. In this post, we will create a Scala program that replaces all occurrences of a specified substring with another substring in a given string.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Obtain the main string and the substring to be replaced, as well as the replacement substring.

4. Implement a function to perform the replacement.

5. Invoke the function and display the result.

6. Execute the program.

3. Code Program

object ReplaceSubstringApp {
  def main(args: Array[String]): Unit = {
    // Input string and substrings
    val originalString = "Hello, World! World is round."
    val substringToReplace = "World"
    val replacementSubstring = "Earth"

    println(s"Original String: $originalString")
    println(s"Substring to Replace: $substringToReplace")
    println(s"Replacement Substring: $replacementSubstring")

    // Replace and print the result
    val resultString = replaceSubstring(originalString, substringToReplace, replacementSubstring)
    println(s"\nResultant String: $resultString")
  }

  // Function to replace all occurrences of a substring
  def replaceSubstring(original: String, target: String, replacement: String): String = {
    original.replace(target, replacement)
  }
}

Output:

Original String: Hello, World! World is round.
Substring to Replace: World
Replacement Substring: Earth
Resultant String: Hello, Earth! Earth is round.

Explanation:

1. We begin the program with an object named ReplaceSubstringApp. Inside this object, the main method serves as the starting point.

2. We then declare originalString, substringToReplace, and replacementSubstring with their respective values.

3. The program then displays the original string, the substring to be replaced, and the replacement substring.

4. The replaceSubstring function is designed to replace all occurrences of the target substring with the replacement substring in the original string.

5. Within the main method, the program calls the replaceSubstring method, performs the replacement, and then showcases the resultant string.

6. The output highlights the transformed string after replacing the specified substring with the desired replacement.


Comments