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:

  1. 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"

  1. Next, use the contains function on the text variable to check if it contains a specific substring. Pass the substring you want to check as an argument to the contains function. The contains 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.

  1. 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.