Strangelove
Strangelove

Reputation: 791

Kotlin: String contains one of particular symbols

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

Answers (3)

clementiano
clementiano

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

Eamon Scullion
Eamon Scullion

Reputation: 1384

Will print true if string contains any of the following ('.', '$', '!)

val illegalCharacters = setOf('.', '$', '!')
print(string.any(illegalCharacters::contains))

Upvotes: 2

yole
yole

Reputation: 97168

myString.indexOfAny(charArrayOf('.', '$', '!')) >= 0

Upvotes: 4

Related Questions