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

前端 未结 4 1691
死守一世寂寞
死守一世寂寞 2021-02-05 01:47

Example:

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

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

相关标签:
4条回答
  • 2021-02-05 02:03

    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.

    0 讨论(0)
  • 2021-02-05 02:04

    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.

    0 讨论(0)
  • 2021-02-05 02:06

    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)
    
    0 讨论(0)
  • 2021-02-05 02:25

    See the contains method in the documentation.

    String1.contains(String2);
    
    0 讨论(0)
提交回复
热议问题