Scala String replaceFirst() Method with Example

Here, we will learn about the replaceFirst() method in Scala. The replaceFirst() method is used to find and replace the first 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 replaceFirst() Method

The replaceFirst() method on strings is used to replace the first occurrence of the given substring with another given string. The substring can be a proper string or a pattern to be matched.

Syntax:

string.replaceFirst(replaceString, newString)

Parameters: The method accepts two parameters. One the substring to be replaced in the string, other one is the string which replaces the substring.

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

Example 1: Program to illustrate the working of the method

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

Output:

The string is ' Scala Programming language''
The string after replace operation 'Scala*Programming language''

Example 2: Program to illustrate the working of the method

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

Output:

The string is ' Scala Programming language'
The string after replace operation '* Programming language'

In the above code, you can see that the string to be replaced is not a full string but instead is a pattern, i.e. it takes any two characters that are before the sub-string matching 'ala'. Hence, it took scala and replaced it with a *.




Comments and Discussions!

Load comments ↻






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