This article explores different ways to check if a string is a substring of another string in Kotlin.

1. Using contains() function

The idiomatic way to check whether a string contains a substring is using the in operator. It returns true if the string contains the specified string, false otherwise.

Download Code

 
This is equivalent to calling the contains() function, but is more concise and readable.

Download Code

 
The contains() function provides an option to make case-insensitive while comparing strings.

Download Code

2. Using indexOf() function

The indexOf() function returns the index of the first occurrence of a substring in the string, and returns -1 if the substring is not found. It can be used as follows to return a boolean value:

Download Code

3. Using Regular Expression

Finally, we can have a RegEx to check a substring within a string. This is demonstrated below, using a matcher to match a string with the substring:

Download Code

 
To ignore the character case by compiling the RegEx with the Pattern.CASE_INSENSITIVE flag, as shown below:

Download Code

That’s all about checking if a string is a substring of another string in Kotlin.