w3resource

Scala Programming: Replace a specified character with another character

Scala Programming String Exercise-10 with Solution

Write a Scala program to replace a specified character with another character.

Sample Solution:

Scala Code:

object Scala_String {
  def main(args: Array[String]): Unit = {
    val str = "The quick brown fox jumps over the lazy dog.";

    // Replace all the 'd' characters with 'f' characters.
    val new_str = str.replace('d', 'f');
    // Display the strings for comparison.
    println("Original string: " + str);
    println("New String: " + new_str);
  }
}

Sample Output:

Original string: The quick brown fox jumps over the lazy dog.
New String: The quick brown fox jumps over the lazy fog.

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to compare a given string to another string, ignoring case considerations.
Next:Write a Scala program to get a substring of a given string between two specified positions.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.