Kotlin String - replace() Function



The Kotlin string replace() function is used to replace a substing or character in a string with a specified replacement character. It offers several overloaded versions to handle different use cases.

Following are the use cases where we can use the replace() function −

  • It can replace old characters with new characters.
  • It can replace all occurrences of the oldValue substring in this string with the specified newValue string.
  • It can replace each substring of this char sequence that matches the given regular expression with the given replacement.
  • It can replace each substring of this char sequence with a new string that matches the given regular expression. The new string is created by a function called "transform" that takes the matching details and generates the replacement.

Syntax

Following is the syntax of the Kotlin string replace() function −

// replace a substring.
fun String.replace(oldValue: String, newValue: String, ignoreCase: Boolean = false): String
// replace a character
fun String.replace(oldChar: Char, newChar: Char, ignoreCase: Boolean = false): String
// replace using regular expressions
fun String.replace(regex: Regex, replacement: String): String

Parameters

This function accepts the following parameters −

  • oldValue: The substring or character to be replaced.
  • newValue: The substring or character to replace old value.
  • ignoreCase: It ignore the case sensitive. By default it is false.

Return value

This function returns a string.

Example 1: Replace a Substring with Another

Following is the basic example, we replace substring of the string using the replace() function −

fun main() {
   val string = "ThiS is tutorialSpoint!"
   // replace substring
   val newString = string.replace("This is", "Hello", ignoreCase = true)
   println(newString)
}

Output

Following is the output −

Hello tutorialSpoint!

Example 2: Replace with Case-Insensitive Char

Here, in this example, we replace characters from the string, whether it is in uppercase or lowercase −

fun main() {
   val string = "ThiS is tutorialSpoint!"
   val newString = string.replace('s', 'x', ignoreCase = true)
   println(newString)
}

Output

Following is the output −

Thix ix tutorialxpoint!

Example 3: Replace Using Regex

The below example, uses the replace() function to replace each character using regular expressions −

fun main() {
   val text = "123-456-789"
   val result = text.replace(Regex("\\d"), "#")
   println(result)
}

Output

Following is the output −

###-###-###
kotlin_strings.htm
Advertisements