Kotlin adds the substringBefore, substringBeforeLast, substringAfter and
substringAfterLast extension functions to the String class.
Instead of using indices to get a substring you can use a string or character value.
The functions without Last use the first occurrence of the delimiter and the
methods with Last use the last occurrence.
If the delimiter is not found the original string is returned.
You can supply a value that should be returned when the delimiter is not found.
The following example code uses the extension functions in several use cases:
val s = "Kotlin Kandy Blogpost"
// Get the substring after a given delimiter character.
assert(s.substringAfter(delimiter = ' ') == "Kandy Blogpost")
// Get the substring after a given delimiter string.
assert(s.substringAfter("Kotlin ") == "Kandy Blogpost")
// When the delimiter is not found the original string is returned.
assert(s.substringAfter(delimiter = '!') == "Kotlin Kandy Blogpost")
// Use a second argument that should be returned if
// the delimiter is not found.
assert(s.substringAfter(delimiter = '!', missingDelimiterValue = "not found") == "not found")
assert(s.substringAfter("Java", "Joy") == "Joy")
// If delimiter appears more than once using substringAfterLast
// will return the value after the last occurrence of the delimiter.
assert(s.substringAfterLast(delimiter = ' ') == "Blogpost")
// Get the substring before a given delimiter character.
assert(s.substringBefore(delimiter = ' ') == "Kotlin")
// Get substring before a given delimiter string.
assert(s.substringBefore("Kandy") == "Kotlin ")
// When the delimiter is not found the original string is returned.
assert(s.substringBefore(delimiter = '!') == "Kotlin Kandy Blogpost")
// Use a second argument that should be returned if
// the delimiter is not found.
assert(s.substringBefore('@', missingDelimiterValue = "not found") == "not found")
// If delimiter appears more than once using substringBeforeLast
// will return the value before the last occurrence of the delimiter.
assert(s.substringBeforeLast(delimiter = ' ') == "Kotlin Kandy")
Written with Kotlin 2.3.20.