ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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 *.

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.