Check if a string contains any of given substrings in Kotlin
This article explores different ways to check if a string contains any of the given substrings in Kotlin.
The idea is to call the contains() function to match against each substring. There are several ways to do this, which are covered below in detail:
1. Using Loop
The following solution creates a utility function that returns true on the first match of the substring from the specified list, using a loop.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun findMatch(s: String, strings: List<String>): Boolean { for (substring in strings) { if (s.contains(substring)) { return true } } return false } fun main() { val today = "Wednesday" val weekend = listOf("Sat", "Sun") println(if (findMatch(today, weekend)) "Yes" else "No") // No } |
To get the actual substring contained in the string, do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun findMatch(s: String, strings: List<String>): String? { for (substring in strings) { if (s.contains(substring)) { return substring } } return null } fun main() { val today = "Saturday" val weekend = listOf("Sat", "Sun") println(findMatch(today, weekend)) // Sat } |
2. Using any() function
The idea here is to call the any() function on the list, which returns true if any item matches the provided predicate. To check if a string contains a substring, use the contains() function as the predicate.
|
1 2 3 4 5 6 7 8 9 |
fun findMatch(s: String, strings: List<String>): Boolean { return strings.any { s.contains(it) } } fun main() { val today = "Wednesday" val weekend = listOf("Sat", "Sun") println(if (findMatch(today, weekend)) "Yes" else "No") // No } |
To get the actual substring contained in the string, use the first() function with the contains() function:
|
1 2 3 4 5 6 7 8 9 |
fun findMatch(s: String, strings: List<String>): String? { return strings.first { s.contains(it) } } fun main() { val today = "Saturday" val weekend = listOf("Sat", "Sun") println(findMatch(today, weekend)) // Sun } |
That’s all about checking if a string contains any of the given substrings in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)