string 如何在 Kotlin 中检查字符串是否包含子字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51238456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:39:09  来源:igfitidea点击:

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

stringkotlin

提问by Anisuzzaman Babla

Example:

例子:

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

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

我想检查 String1 是否包含 String2。

回答by Aseem Sharma

Kotlin has stdlibpackage 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

Kotlin 有stdlib包对字符串执行某些扩展函数操作,您可以检查此方法它会检查字符串中的子字符串,您可以通过传递真/假值来忽略大小写。参考这个链接

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

回答by yole

The most idiomatic way to check this is to use the inoperator:

检查这一点最惯用的方法是使用in运算符:

String2 in String1

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

这相当于调用contains(),但更短且更易读。

回答by htuy42

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

Kotlin 在字符串上有几个不同的 contains 函数,请参见此处: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.

如果您希望 string2 包含在 string1 中是真的(即您想忽略大小写),它们甚至为您提供了一个方便的布尔参数,因此您无需先转换为小写。

回答by William Burnham

See the containsmethod in the documentation.

请参阅文档中contains方法。

String1.contains(String2);