0
0
KotlinHow-ToBeginner · 3 min read

How to Check if String Contains Substring in Kotlin

In Kotlin, you can check if a string contains a substring using the contains() function. It returns true if the substring is found and false otherwise. You can also specify if the check should ignore case by passing true to the ignoreCase parameter.
📐

Syntax

The contains() function checks if a string includes a given substring.

  • substring: The text you want to find inside the main string.
  • ignoreCase (optional): A boolean to ignore case differences. Default is false.
kotlin
val mainString = "Hello Kotlin"
val substring = "Kotlin"

val result = mainString.contains(substring)  // returns true

// Case insensitive check
val resultIgnoreCase = mainString.contains("kotlin", ignoreCase = true)  // returns true
💻

Example

This example shows how to check if a string contains a substring with and without ignoring case.

kotlin
fun main() {
    val text = "Learning Kotlin is fun"
    val word1 = "Kotlin"
    val word2 = "java"

    println(text.contains(word1))           // true
    println(text.contains(word2))           // false
    println(text.contains("kotlin", ignoreCase = true)) // true (ignores case)
}
Output
true false true
⚠️

Common Pitfalls

One common mistake is forgetting that contains() is case-sensitive by default, so "Kotlin" and "kotlin" are treated differently. Another is using == instead of contains(), which checks for exact equality, not substring presence.

kotlin
fun main() {
    val text = "Hello Kotlin"

    // Wrong: checks if whole string equals substring
    println(text == "Kotlin")  // false

    // Right: checks if substring exists
    println(text.contains("Kotlin"))  // true

    // Case sensitive check fails
    println(text.contains("kotlin"))  // false

    // Case insensitive check succeeds
    println(text.contains("kotlin", ignoreCase = true))  // true
}
Output
false true false true
📊

Quick Reference

FunctionDescriptionExample
contains(substring: String)Checks if substring exists (case-sensitive)"Hello".contains("ell") // true
contains(substring: String, ignoreCase: Boolean)Checks if substring exists, ignoring case if true"Hello".contains("HELLO", ignoreCase = true) // true

Key Takeaways

Use the contains() function to check if a string includes a substring in Kotlin.
By default, contains() is case-sensitive; use ignoreCase = true to ignore case.
Avoid using == when you want to check for substring presence.
contains() returns a Boolean: true if found, false if not.
Remember to pass the substring as a String argument to contains().