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.
String2 !in String1. You do not need parentheses.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. :)
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.
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!
}
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
}
}