How to check if a string has only one of the specified character?

Viewed 89

I know that I can use .contains() to check if a string has a particular character, but I want to check if a string has only one of the character.

For example, if I check for 'a', I want it to return true for "abb" but false for "aabb"

How do I do that?

2 Answers

In Kotlin we can solve as below:

var ss : CharSequence  = "abdaaa"
val isValid =  ss.filter { item -> item.equals('a', false) }.length == 1

You can use the count{} to do that:

ss.count {it == 'a' }

It counts the number of a in ss, to check with 1 , you can just:

ss.count {it == 'a' } == 1
Related