Scala String replaceAll() Method with Example

Here, we will learn about the replaceAll() method in Scala. The replaceAll() method is used to find and replace the all occurrence of the given string in Scala.
Submitted by Shivang Yadav, on January 29, 2021

String is an immutable collection that stores sequences of characters.

String replaceAll() Method

The replaceAll() method on strings is used to replace all occurrences of the given substring with another string. The substring to be replaced can be a proper string or a pattern to be matched.

Syntax:

string.replaceAll(replaceString, newString)

Parameters: The method accepts two parameters; one is the substring to be replaced and other is the string which is going to replace the substring.

Return Value: It returns a string which is the string created after performing the replace operation.

Example 1: Replace all method, search for a perfect substring

object myObject {
    def main(args: Array[String]) {
        val myString = "Scala Programming language"
        println("The string is ' " + myString + "'")
        
        val newString = myString.replaceAll("a", "*")
        println("The string after replace operation '" + newString + "'")
    }
}

Output:

The string is ' Scala Programming language'
The string after replace operation 'Sc*l* Progr*mming l*ngu*ge'

Example 2: Replace all method, search for a pattern match

object myObject {
    def main(args: Array[String]) {
        val myString = "Scala Programming language"
        println("The string is ' " + myString + "'")
        
        val newString = myString.replaceAll(".a", "**")
        println("The string after replace operation '" + newString + "'")
    }
}

Output:

The string is ' Scala Programming language'
The string after replace operation 'S**** Prog**mming **ng**ge'




Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.