Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

kotlin string helpers to find index in a string where any element of another string matches first/last etc

C++ has string functions like find_first_of(), find_first_not_of(), find_last_of(),
find_last_not_of(). e.g. if I write

string s {"abcdefghi"};
  • s.find_last_of("eaio") returns the index of i

  • s.find_first_of("eaio") returns the index of a

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  • s.find_first_not_of("eaio") returns the index of b

Does Kotlin has any equivalent.

>Solution :

Kotlin doesn’t have these exact functions, but they are all special cases of indexOfFirst and indexOfLast:

fun CharSequence.findFirstOf(chars: CharSequence) = indexOfFirst { it in chars }
fun CharSequence.findLastOf(chars: CharSequence) = indexOfLast { it in chars }
fun CharSequence.findFirstNotOf(chars: CharSequence) = indexOfFirst { it !in chars }
fun CharSequence.findLastNotOf(chars: CharSequence) = indexOfLast { it !in chars }

These will return -1 if nothing is found.

Usage:

val s = "abcdefghi"
val chars = "aeiou"
println(s.findFirstOf(chars))
println(s.findFirstNotOf(chars))
println(s.findLastOf(chars))
println(s.findLastNotOf(chars))

Output:

0
1
8
7
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading