简体   繁体   中英

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.

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)

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.

You can do it by using the "in" - operator, eg

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

check has the value true then. :)

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.

请参阅文档中contains方法。

String1.contains(String2);

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!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM