tak*_*a15 11 arrays string contains kotlin
我是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
}
Run Code Online (Sandbox Code Playgroud)
作为一个开始(这忽略'匹配'变量并获得匹配关键字列表),我尝试使用以下if语句根据我在此问题中找到的,
if(Arrays.stream(keywords).parallel().anyMatch(content::contains))
Run Code Online (Sandbox Code Playgroud)
但它在"内容"下面放了一条波浪线,给了我这个错误
使用提供的参数不能调用以下函数:public operator fun CharSequence.contains(char:Char,ignoreCase:Boolean = ...):在kotlin.text中定义的布尔值公共运算符fun CharSequence.contains(其他:CharSequence, ignoreCase:Boolean = ...):在kotlin.text中定义的Boolean @InlineOnly public inline operator fun CharSequence.contains(regex:Regex):在kotlin.text中定义的Boolean
Ily*_*lya 12
您可以使用该filter函数仅保留以下所包含的关键字content:
val match = keywords.filter { it in content }
Run Code Online (Sandbox Code Playgroud)
这match是一个List<String>.如果要在结果中获取数组,可以添加.toTypedArray()调用.
in表达式it in content中的运算符是一样的content.contains(it).
如果要进行不区分大小写的匹配,则需要ignoreCase在调用时指定参数contains:
val match = keywords.filter { content.contains(it, ignoreCase = true) }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4314 次 |
| 最近记录: |