Kotlin program to check if a string contains another substring

Published by admin on

Introduction :

In this kotlin programming tutorial, we will learn how to check if a substring exists in another string or not. The program will take the strings as input from the user and print out the result.

We will learn how to check if the string contains a substring by ignoring all case of each character during the checking and by not ignoring the case.

 

Kotlin contains method :

Kotlin String class has one method called contains to check if a string contains another substring or not. It takes two arguments :

1. The first argument is the substring that we need to check.

2. The second argument is one boolean value ignoreCase. If true, the checking will ignore all character case, else if false, it will not ignore the character case.

Below examples will add more clarity to you :

 

Check substring in a string without ignoring case :

Let’s try to implement the contains method by not ignoring all character case :

fun main(args: Array) {
    val line: String
    val subStr: String

    print("Enter a string : ")
    line = readLine().toString()

    print("Enter a sub string : ")
    subStr = readLine().toString()

    if (line.contains(subStr, false)) {
        print("String '$line' contains substring '$subStr'")
    } else {
        print("String '$line' doesn't contain substring '$subStr'")
    }
}

kotlin check substring in string
The output of the above program will look like below :

Enter a string : Hello World
Enter a sub string : Hello
String 'Hello World' contains substring 'Hello'

Enter a string : Hello World
Enter a sub string : hello
String 'Hello World' doesn't contain substring 'hello'

As you can see, if we are passing false to the contains method, it checks the character case while comparing.

 

Check substring in a string ignoring case :

For checking substring in a string ignoring case, the only thing we need to do is pass true instead of false as the above example.

fun main(args: Array) {
    val line: String
    val subStr: String

    print("Enter a string : ")
    line = readLine().toString()

    print("Enter a sub string : ")
    subStr = readLine().toString()

    if (line.contains(subStr, true)) {
        print("String '$line' contains substring '$subStr'")
    } else {
        print("String '$line' doesn't contain substring '$subStr'")
    }
}

Sample Output :

Enter a string : Hello World
Enter a sub string : Hello
String 'Hello World' contains substring 'Hello'

Enter a string : Hello String
Enter a sub string : hello
String 'Hello String' contains substring 'hello'

Conclusion :

We have learned how to check if a substring exists in a string or not in Kotlin. Try to run both examples we have shown above and drop one comment below if you have any queries.

Categories: kotlin

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *