Skip to content

Instantly share code, notes, and snippets.

@kiwiandroiddev
Created July 11, 2019 00:16
Show Gist options
  • Save kiwiandroiddev/ce8920d94edf81dddd8c1893a51c44b8 to your computer and use it in GitHub Desktop.
Save kiwiandroiddev/ce8920d94edf81dddd8c1893a51c44b8 to your computer and use it in GitHub Desktop.
Kotlin extension function on String to find all instances of given substring within. Results are in the form of a list of index pairs.
/**
* Find all instances of given substring in this string.
* Results are in the form of a list of index pairs (start and end index of that particular match).
*/
fun String.findAllInstancesOf(
subString: String,
startIndex: Int = 0
): List<Pair<Int, Int>> {
val index = this.indexOf(subString, startIndex)
if (index == -1) return emptyList()
return listOf(index to index + subString.length)
.plus(this.findAllInstancesOf(subString, index + 1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment