Home > database >  kotlin string helpers to find index in a string where any element of another string matches first/la
kotlin string helpers to find index in a string where any element of another string matches first/la

Time:11-21

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

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

Does Kotlin has any equivalent.

CodePudding user response:

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
  • Related