Home »
Scala
Scala String replace() Method
By IncludeHelp Last updated : October 22, 2024
Description and Usage
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,
- The character to be replaced in the string.
- 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.