Created
July 11, 2019 00:16
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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