1

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.

1
  • @Sweeper You are right. Thanks for pinpointing the mistake. I have corrected it. Commented Nov 20, 2021 at 10:18

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.