Check whether a String contains a character in Kotlin
This article explores different ways to check whether a String contains a character in Kotlin.
1. Using indexOf() function
The indexOf() function returns the index of the first occurrence of a char within the string. If the character does not exist, it returns -1. This value can be used to check if the given character appears in the string or not, as shown below:
|
1 2 3 4 5 6 7 |
fun main() { val s = "Kotlin" val c = 'o' val isExist = s.indexOf(c) != -1 println(isExist) // true } |
2. Using contains() function
Alternatively, we can use the contains() function to check if a char is present in the string or not.
|
1 2 3 4 5 6 7 |
fun main() { val s = "Kotlin" val c = 'o' val isExist = s.contains(c) println(isExist) // true } |
We can make the comparison case-insensitive, as follows:
|
1 2 3 4 5 6 7 |
fun main() { val s = "Kotlin" val c = 'k' val isExist = s.contains(c, ignoreCase = true) println(isExist) // true } |
3. Using in operator
The most idiomatic way to check if a string contains a character is using the in operator. This is equivalent to calling the contains() function, but offers shorter and more readable syntax.
|
1 2 3 4 5 6 7 |
fun main() { val s = "Kotlin" val c = 'o' val isExist = c in s println(isExist) // true } |
That’s all about checking whether a String contains a character 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 :)