How to check whether a string contains a substring

2020-05-25 07:18发布

问题:

Example:

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

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

回答1:

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)


回答2:

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.



回答3:

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.



回答4:

See the contains method in the documentation.

String1.contains(String2);


标签: string kotlin