virus00x
virus00x

Reputation: 743

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"};

Does Kotlin has any equivalent.

Upvotes: 1

Views: 789

Answers (1)

Sweeper
Sweeper

Reputation: 270995

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

Upvotes: 3

Related Questions