kotlin check if string contains
To check if a string contains a specific substring in Kotlin, you can use the contains
function. Here are the steps to do it:
- Start by declaring a string variable that you want to check. For example, let's say you have a string variable called
text
that contains the main string you want to search in.
kotlin
val text = "This is a sample string"
- Next, use the
contains
function on thetext
variable to check if it contains a specific substring. Pass the substring you want to check as an argument to thecontains
function. Thecontains
function returns a boolean value indicating whether the substring is found or not.
kotlin
val substring = "sample"
val containsSubstring = text.contains(substring)
In this example, we are checking if the text
variable contains the substring "sample". The result will be stored in the containsSubstring
variable.
- Finally, you can use the
containsSubstring
variable to determine if the string contains the substring. You can print the result or use it in your logic accordingly.
kotlin
if (containsSubstring) {
println("The string contains the substring.")
} else {
println("The string does not contain the substring.")
}
This code will print "The string contains the substring." if the substring is found in the string, or "The string does not contain the substring." if the substring is not found.
That's it! By following these steps, you can check if a string contains a specific substring in Kotlin.