Reputation: 791
I need to check if my string contains one (or more) symbols from set (assuming that ".", "$", "!"). How to check it without iteration of each symbol?
Upvotes: 0
Views: 3991
Reputation: 139
There is a simple method to do this in kotlin
val stringVal = "Hello, World!"
val containsSymbol = stringVal.findAnyOf(strings = listOf(".", "$", "!"), startIndex = 0, ignoreCase = false) != null
It can be made into an extension function if you like
fun String.containsSymbol(symbols: List<String>, startIndex: Int = 0, ignoreCase: Boolean = false): Boolean {
return this.findAnyOf(symbols, 0, false) != null
}
Can be invoked like this "Hello world".containsSymbol(listOf(".", "$", "!"))
Upvotes: 0
Reputation: 1384
Will print true if string
contains any of the following ('.', '$', '!)
val illegalCharacters = setOf('.', '$', '!')
print(string.any(illegalCharacters::contains))
Upvotes: 2