【发布时间】:2018-11-20 04:18:07
【问题描述】:
我是 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
}
作为开始(这会忽略“匹配”变量并获取匹配的关键字列表),我尝试根据我在 this question 找到的内容使用以下 if 语句,
if(Arrays.stream(keywords).parallel().anyMatch(content::contains))
但它在“内容”下放了一条波浪线并给了我这个错误
以下函数都不能使用参数调用 提供:公共运营商 fun CharSequence.contains(char: Char, ignoreCase: Boolean = ...): Boolean 定义在 kotlin.text public 运算符 fun CharSequence.contains(other: CharSequence, ignoreCase: Boolean = ...):在 kotlin.text @InlineOnly public 中定义的布尔值 内联运算符 fun CharSequence.contains(regex: Regex): Boolean 在 kotlin.text 中定义
【问题讨论】:
标签: arrays string kotlin contains