Check if a string is a substring of another string in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 |
fun isSubstring(str: String, seq: String): Boolean { return seq in str } fun main() { val str = "Techie" val seq = "Tech" println(if (isSubstring(str, seq)) "Yes" else "No") // Yes } |
This is equivalent to calling the contains() function, but is more concise and readable.
|
1 2 3 4 5 6 7 8 9 |
fun isSubstring(str: String, seq: String): Boolean { return str.contains(seq) } fun main() { val str = "Techie" val seq = "Tech" println(if (isSubstring(str, seq)) "Yes" else "No") // Yes } |
The contains() function provides an option to make case-insensitive while comparing strings.
|
1 2 3 4 5 6 7 8 9 10 |
fun isSubstring(str: String, seq: String): Boolean { return str.contains(seq, ignoreCase = true) } fun main() { val str = "Techie" val seq = "tech" println(if (isSubstring(str, seq)) "Yes" else "No") // Yes } |
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:
|
1 2 3 4 5 6 7 8 9 10 |
fun isSubstring(str: String, seq: String): Boolean { return str.indexOf(seq) != -1 } fun main() { val str = "Techie" val seq = "Tech" println(if (isSubstring(str, seq)) "Yes" else "No") // Yes } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.regex.Pattern fun isSubstring(str: String, seq: String): Boolean { return Pattern.compile(seq).matcher(str).find() } fun main() { val str = "Techie" val seq = "Tech" println(if (isSubstring(str, seq)) "Yes" else "No") // Yes } |
To ignore the character case by compiling the RegEx with the Pattern.CASE_INSENSITIVE flag, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.regex.Pattern fun isSubstring(str: String, seq: String): Boolean { return Pattern.compile(seq, Pattern.CASE_INSENSITIVE).matcher(str).find() } fun main() { val str = "Techie" val seq = "tech" println(if (isSubstring(str, seq)) "Yes" else "No") // Yes } |
That’s all about checking if a string is a substring of another string 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 :)