In this tutorial, you shall learn how to check if a given string contains specific search string in Kotlin, using String.contains() function, with examples.
Kotlin – Check if string contains specific search string
To check if a string contains specified string in Kotlin, use String.contains() method.
Given a string str1
, and if we would like to check if the string str2
is present in the string str1
, call contains() method on string str1
and pass the the string str2
as argument to the method as shown below.
str1.contains(str2)
contains() method returns true if the string str2
is present in the string str1
, else it returns false.
Examples
1. String contains specified search string
In this example, we will take two strings in str1
and str2
, and check if the string str1
contains the string str2
using String.contains() method.
Kotlin Program
fun main(args: Array<String>) {
val str1 = "abcdef"
val str2 = "cd"
val result = str1.contains(str2)
println("The result of str1.contains(str2) is: " + result)
if (result) {
println("String str1 contains the string str2.")
} else {
println("String str1 does not contain the string str2.")
}
}
Output
The result of str1.contains(str2) is: true
String str1 contains the string str2.
2. Specified search string is not present in given string
In this example, we will take two strings in str1
and str2
such that str2
is not present in str1
. str1.contains(str2) should return false.
Kotlin Program
fun main(args: Array<String>) {
val str1 = "abcdef"
val str2 = "pq"
val result = str1.contains(str2)
println("The result of str1.contains(str2) is: " + result)
if (result) {
println("String str1 contains the string str2.")
} else {
println("String str1 does not contain the string str2.")
}
}
Output
The result of str1.contains(str2) is: false
String str1 does not contain the string str2.
Conclusion
In this Kotlin Tutorial, we learned how to check if given string contains a specified string value in it, using String.contains() method, with the help of Kotlin example programs.