Check if a string starts (or ends) with any of the given substrings in Kotlin
This article explores different ways to check if a string starts or ends with any of the given substrings in Kotlin.
1. Using startsWith() / endsWith() function
A simple solution is to use the startsWith() function to check if a string matches against any of the given substrings with an OR operator. The startsWith() function returns a boolean value depending upon the string starts with the specified substring or not.
|
1 2 3 4 5 6 7 8 |
fun isWeekend(day: String): Boolean { return day.startsWith("Sat") || day.startsWith("Sun") } fun main() { val day = "Sunday" println(if (isWeekend(day)) "Weekend" else "Weekday") // Weekend } |
To check if the string ends with the specified substring or not, use the endsWith() function.
|
1 2 3 4 5 6 |
fun main() { val str = "ABCD" val arr = arrayOf("AB", "BC", "CD") println(str.endsWith(arr[0]) || str.endsWith(arr[1]) || str.endsWith(arr[2])) // true } |
2. Using any() function
A better solution is to construct a list from the given substrings and call the any() function on the list. It returns true if at least one element matches the supplied predicate. To check for “starts with”, use the startsWith() function as predicate.
|
1 2 3 4 5 6 7 8 |
fun isWeekend(day: String): Boolean { return listOf("Sat", "Sun").any { s -> day.startsWith(s) } } fun main() { val day = "Monday" println(if (isWeekend(day)) "Weekend" else "Weekday") // Weekday } |
The following solution replaces the explicit parameter s with it:
|
1 2 3 4 5 6 7 8 |
fun isWeekend(day: String): Boolean { return listOf("Sat", "Sun").any { day.startsWith(it) } } fun main() { val day = "Monday" println(if (isWeekend(day)) "Weekend" else "Weekday") // Weekday } |
To check if the string ends with the specified substring or not, use the endsWith() function.
|
1 2 3 4 5 6 7 8 |
fun matchSuffix(day: String): Boolean { return listOf("AB", "BC", "CD").any { day.endsWith(it) } } fun main() { val day = "ABCD" println(if (matchSuffix(day)) "Match" else "Not-Match") // Match } |
This can also be achieved using a loop. Here’s the equivalent version of the above code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun matchSuffix(day: String): Boolean { for (s in listOf("AB", "BC", "CD")) { if (day.endsWith(s)) { return true } } return false } fun main() { val day = "ABCD" println(if (matchSuffix(day)) "Match" else "Not-Match") // Match } |
That’s all about checking if a string starts or ends with 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 :)