Kotlin – Delete substring from specific start to end in string

Delete substring from specific start to end position in a String in Kotlin

To delete a substring defined from specific a start to end position in a string in Kotlin, you can use String.substring() function.

a  p  p  l  e  _  i  s  _  r  e  d
0  1  2  3  4  5  6  7  8  9  10 11
     start --> 5     7  <-- end
              |<----->|
         delete this substring
a  p  p  l  e           _  r  e  d
 first_part             second_part

Find the substring from beginning of the string till the start position of the substring to delete. This is our first part.

str.substring(0, start)

Then find the substring from after the ending index of the substring to be deleted till the end of the string. This is our second part.

str.substring(end+1)

Join these two parts to create a string formed from the original string with the specified substring deleted.

str.substring(0, start) + str.substring(end+1)

Examples

Delete substring from start=5 and end=7

In the following program, we take a string value in str, and delete the substring form this string whose start index is 5 and end index is 7.

Kotlin Program

fun main() {
    val str = "apple_is_red"
    val start = 5
    val end = 7
    val resultString = str.substring(0, start) + str.substring(end+1)
    println(resultString)
}

Output

apple_red

Explanation

a  p  p  l  e  _  i  s  _  r  e  d
0  1  2  3  4  5  6  7  8  9  10 11
     start --> 5     7  <-- end
              |<----->|
         delete this substring
a  p  p  l  e           _  r  e  d