What is replace in Scala?

Scala offers many methods for string manipulation. One of these methods include replace method.

replace method is used to replace a character in a piece of text. It performs a find-and-replace function.

Parameters

The replace function takes two arguments. The first is the character that is going to be replaced and the second is the character that will replace it.

Syntax

String replace(char oldChar, char newChar)

Return value

The function replace returns a string containing the new character in place of the one that was replaced.

Code

object Educative
{
// Main method
def main(args:Array[String])
{
// Applying replace method for one character
val result1 = "pducative".replace('p', 'E')
// Applying replace method for multiple characters
val result2 = "Edprekko".replace('k', 's')
// Displays output
println(result1)
println(result2)
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved