Sling Academy
Home/Kotlin/How to Check if a String Contains Certain Words in Kotlin

How to Check if a String Contains Certain Words in Kotlin

Last updated: December 05, 2024

When writing Kotlin applications, you may encounter situations where you need to determine whether a string contains certain words or substrings. Fortunately, Kotlin provides several methods that simplify this task. In this article, we will explore multiple ways to check if a string contains a given word or set of words in Kotlin, offering clarity and practical examples along the way.

Using contains() Function

The most straightforward way to check if a string contains another string is by using the contains() function. This function is part of the Kotlin String class and is both simple to use and quite effective.


fun main() {
    val text = "Kotlin is a modern programming language."
    val containsWord = text.contains("modern")

    if (containsWord) {
        println("The string contains the word 'modern'.")
    } else {
        println("The word 'modern' was not found.")
    }
}

In this example, the string text is searched for the word "modern". The function contains() returns true if the string contains the specified substring and false otherwise.

Ignoring Case with contains()

If you want to perform a case-insensitive search, contains() also has an overload that takes an enum of type CharSequence as a parameter.


fun main() {
    val text = "Kotlin is a Modern Programming Language."
    val containsWord = text.contains("modern", ignoreCase = true)

    if (containsWord) {
        println("The string contains the word 'modern', case insensitive.")
    } else {
        println("The word 'modern' was not found.")
    }
}

By setting the ignoreCase parameter to true, the search checks for the word inclusion without being case-sensitive.

Using Regular Expressions

For more complex word searches, you might want to leverage Kotlin's built-in support for regular expressions with the Regex class. This is particularly useful when you need to check for multiple words or patterns.


fun main() {
    val text = "Kotlin is a language with many features."
    val regex = Regex("features|language")
    val containsWords = regex.containsMatchIn(text)

    if (containsWords) {
        println("The string matches the pattern for 'features' or 'language'.")
    } else {
        println("No match was found for the provided patterns.")
    }
}

The Regex class allows you to define patterns and check if any such patterns exist in your string.

Using split() Method

For cases where you might want to check against an independent word rather than a substring, you can split the string into individual words using the split() method and perform a set-based comparison.


fun main() {
    val text = "Kotlin works on JVM"
    val words = text.split(" ")
    if ("JVM" in words) {
        println("The string contains the full word 'JVM'.")
    } else {
        println("The word 'JVM' was not found.")
    }
}

The string is split into a list, and you can check using in to see if any specific words exist in the list, providing a full-word match.

Conclusion

Kotlin offers various utilities for string handling that make it easy to check for the presence of words or substrings. Whether you're using the contains() function, leveraging regular expressions, or splitting strings into lists of words, you have multiple options depending on your needs. Choosing the right method will depend on the specifics of your application such as case sensitivity and the complexity of the search patterns you need. These tools collectively enable developers to write efficient and expressive code when performing string manipulations.

Next Article: Matching Specific Date Formats in Kotlin

Previous Article: Ensuring Strings Meet Length Requirements in Kotlin

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin