Check whether a string contains a substring in Kotlin
This article explores different ways to check whether a string contains a substring in Kotlin.
1. Using contains() function
The standard solution to check if the string contains the specified sequence of characters as a substring is with the contains() function. Here’s an example of its usage:
|
1 2 3 4 5 6 |
fun main() { val s1 = "Kotlin" val s2 = "in" println(s1.contains(s2)) } |
If you need to perform the comparison with the case ignored, you can pass the boolean value true as a second parameter to the contains() function.
|
1 2 3 4 5 6 |
fun main() { val s1 = "Kotlin" val s2 = "IN" println(s1.contains(s2, ignoreCase = true)) } |
2. Using In operator
The Kotlin way to check if a string contains a substring is with the In operator, which provides shorter and more readable syntax. The expression a in b is translated to b.contains(a) and the expression a !in b is translated to !b.contains(a). In other words, In is equivalent to calling the contains() function.
|
1 2 3 4 5 6 |
fun main() { val s1 = "Kotlin" val s2 = "in" println(s2 in s1) } |
That’s all about determining whether a string contains a substring 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 :)