Anisuzzaman Babla
Anisuzzaman Babla

Reputation: 7480

How to check whether a string contains a substring in Kotlin?

Example:

String1 = "AbBaCca";
String2 = "bac";

I want to perform a check that String1 contains String2 or not.

Upvotes: 70

Views: 119331

Answers (7)

Oleg Daniv
Oleg Daniv

Reputation: 1

in my case works codingjeremy answer, with littel changes:

operator fun String?.contains(substring: String?): Boolean {
 return if (this != null && substring != null) {
 val charSequence: CharSequence = this
   charSequence.contains(substring)
   } else {
   false
   }
 }

Upvotes: 0

codingjeremy
codingjeremy

Reputation: 5741

For anyone out there like me who wanted to do this for a nullable String, that is, String?, here is my solution:

operator fun String?.contains(substring:String): Boolean {
    return if (this is String) {
        // Need to convert to CharSequence, otherwise keeps calling my
        // contains in an endless loop.
        val charSequence: CharSequence = this
        charSequence.contains(substring)
    } else {
        false
    }
}

// Uses Kotlin convention of converting 'in' to operator 'contains'
if (shortString in nullableLongString) {
    // TODO: Your stuff goes here!
}

Upvotes: 1

Apix_D
Apix_D

Reputation: 1101

You can do it by using the "in" - operator, e.g.

val url : String = "http://www.google.de"
val check : Boolean = "http" in url

check has the value true then. :)

Upvotes: 17

yole
yole

Reputation: 97138

The most idiomatic way to check this is to use the in operator:

String2 in String1

This is equivalent to calling contains(), but shorter and more readable.

Upvotes: 82

Aseem Sharma
Aseem Sharma

Reputation: 1853

Kotlin has stdlib package to perform certain extension function operation over the string, you can check this method it will check the substring in a string, you can ignore the case by passing true/false value. Refer this link

"AbBaCca".contains("bac", ignoreCase = true)

Upvotes: 108

geco17
geco17

Reputation: 5294

See the contains method in the documentation.

String1.contains(String2);

Upvotes: 4

htuy42
htuy42

Reputation: 327

Kotlin has a few different contains function on Strings, see here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/contains.html.

If you want it to be true that string2 is contained in string1 (ie you want to ignore case), they even have a convenient boolean argument for you, so you won't need to convert to lowercase first.

Upvotes: 3

Related Questions