Scala String replace() Method with Example

Here, we will learn about the replace() method in Scala. The replace() method is used to replace characters in the string. We will learn about replace() method, its working, syntax and example.
Submitted by Shivang Yadav, on January 30, 2021

String is an immutable collection that stores sequences of characters.

String replace() Method

The replace() method replaces a character from the given string with a new character.

Syntax:

string_Name.replace(char stringChar, char newChar)

Parameters: The method accepts two parameters,

  1. The character to be replaced in the string.
  2. The character which is placed in place of the old character.

Return Value: It returns a string which contains the replaced character.

Example 1: Replacing character with single occurrence in the string

object MyClass {
    def main(args: Array[String]) {
        val myString = "scala programming language"
        println("The string is '" + myString + "'")
        
        val newString = myString.replace('s', 'S')
        println("The string after replacing the characters is " + newString)
    }
}

Output:

The string is 'scala programming language'
The string after replacing the characters is Scala programming language

Example 2: Replacing character with multiple occurrences in the string

object MyClass {
    def main(args: Array[String]) {
        val myString = "scala programming language"
        println("The string is '" + myString + "'")
        
        val newString = myString.replace('a', 'A')
        println("The string after replacing the characters is " + newString)
    }
}

Output:

The string is 'scala programming language'
The string after replacing the characters is scAlA progrAmming lAnguAge

Example 3: Trying to replace character not present in the string

object MyClass {
    def main(args: Array[String]) {
        val myString = "scala programming language"
        println("The string is '" + myString + "'")
        
        val newString = myString.replace('z', 'Z')
        println("The string after replacing the characters is " + newString)
    }
}

Output:

The string is 'scala programming language'
The string after replacing the characters is scala programming language

In the above code, the string remains as it is there is a match for the given character so nothing is replaced.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.