Kotlin String - replaceRange() Function



The Kotlin string replaceRange() function is used to replace a specific range of characters in a string with a given replacement string. It offers multiple overloaded versions to handle different use cases.

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

  • It replaces the contents of this character sequence where part of it lies at the given range.
  • It replaces the part of the string at the given range with the replacement string.
This function cannot modify the string because string is immutable in Kotlin, so the original string remains unchanged and returns a new string where the specified range of characters is replaced by replacement.

Syntax

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

fun String.replaceRange(range: IntRange, replacement: String): String
fun String.replaceRange(startIndex: Int, endIndex: Int, replacement: String): String

Parameters

This function accepts the following parameters −

  • range: The range of character indices to be replaced.
  • replacement: The substring that will replace the character in the specified range.

This function also accepts the following parameters when we need to specify the startIndex or endIndex.

  • startIndex: The starting index (inclusive) of the range to replace.
  • endIndex: The ending index (exclusive) of the range to replace.
  • replacement: The string that will replace the characters in the specified range.

Return value

This function returns a string or character sequence.

Example 1

In this basic example, we replace the string with a new string by specifying the intRange to the replaceRange() function −

fun main() {
   val string = "This is tutorialSpoint! "
   // replace in range
   val newString = string.replaceRange(4..9, " Hello ")
   println(newString)
}

Output

Following is the output −

This Hello torialSpoint!

Example 2

Here, we pass the value of the startIndex and endIndex respectively to the replaceRange() function −

fun main() {
   val charSequence = "Hello Kotlin"
   // specify the start and end index
   val new_char_seq = charSequence.replaceRange(6, 12, "World")
   println(new_char_seq)
}

Output

Following is the output −

Hello World

Example 3: Replace a String with an Empty String

If replacement is an empty string, this function will create a new string by removing the specified range from the original string −

fun main() {
   val string = "Hello tutorialspoint"
   // specify the range
   val new_string = string.replaceRange(6..13, "")
   println("This is the new string: "+new_string)
}

Output

Following is the Output −

This is the new string: Hello spoint
kotlin_strings.htm
Advertisements