Home »
Scala
Scala String replaceFirst() Method
By IncludeHelp Last updated : October 22, 2024
Description and Usage
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
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
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 *.