我刚接触Kotlin(我有Java背景),但似乎无法弄清如何检查字符串是否包含关键字列表中的匹配项。
我的目标是检查字符串是否包含来自关键字数组的匹配项(忽略大小写)。如果是这样,请打印出与关键字匹配的关键字和包含该关键字的字符串。(我将循环遍历文件中的一堆字符串)。
这是一个MVE:
val keywords = arrayOf("foo", "bar", "spam")
fun search(content: String) {
var match = <return an array of the keywords that content contained>
if(match.size > 0) {
println("Found match(es): " + match + "\n" + content)
}
}
fun main(args: Array<String>) {
var str = "I found food in the barn"
search(str) //should print out that foo and bar were a match
}
作为一个开始(这忽略了“match”变量和获取匹配关键字列表),我尝试使用以下if语句,根据我在这个问题中找到的内容进行调整。
if(Arrays.stream(keywords).parallel().anyMatch(content::contains))
但它在“content”下面放了一条波浪线,并给了我这个错误:
无法使用提供的参数调用以下任何函数:public operator fun CharSequence.contains(char: Char, ignoreCase: Boolean = ...): Boolean defined in kotlin.text public operator fun CharSequence.contains(other: CharSequence, ignoreCase: Boolean = ...): Boolean defined in kotlin.text @InlineOnly public inline operator fun CharSequence.contains(regex: Regex): Boolean defined in kotlin.text