string 检查列表中的值是否是字符串的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16046146/
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
Checking if values in List is part of String
提问by Sibi
I have a string like this:
我有一个这样的字符串:
val a = "some random test message"
I have a list like this:
我有一个这样的清单:
val keys = List("hi","random","test")
Now, I want to check whether the string a
contains any values from keys
. How can we do this using the in built library functions of Scala ?
现在,我想检查字符串是否a
包含来自keys
. 我们如何使用 Scala 的内置库函数来做到这一点?
( I know the way of splitting a
to List and then do a check with keys
list and then find the solution. But I'm looking a way of solving it more simply using standard library functions.)
(我知道拆分a
为 List 的方法,然后使用keys
list进行检查,然后找到解决方案。但我正在寻找一种使用标准库函数更简单地解决它的方法。)
回答by rarry
Something like this?
像这样的东西?
keys.exists(a.contains(_))
Or even more idiomatically
或者更地道
keys.exists(a.contains)
回答by Rick-777
The simple case is to test substring containment (as remarked in rarry
's answer), e.g.
简单的情况是测试子字符串包含(如rarry
的答案中所述),例如
keys.exists(a.contains(_))
You didn't say whether you actually want to find whole word matches instead. Since rarry
's answer assumed you didn't, here's an alternative that assumes you do.
你没有说你是否真的想找到整个单词匹配。由于rarry
的回答假设您没有,这里有一个假设您有的替代方案。
val a = "some random test message"
val words = a.split(" ")
val keys = Set("hi","random","test") // could be a List (see below)
words.exists(keys contains _)
Bear in mind that the listof keys is only efficient for small lists. With a list, the contains
method typically scans the entire list linearly until it finds a match or reaches the end.
请记住,键列表仅对小列表有效。对于列表,该contains
方法通常线性扫描整个列表,直到找到匹配项或到达末尾。
For larger numbers of items, a set is not only preferable, but also is a more true representation of the information. Sets are typically optimised via hashcodes etc and therefore need less linear searching - or none at all.
对于数量较多的项目,集合不仅更可取,而且是信息的更真实表示。集合通常通过哈希码等进行优化,因此需要较少的线性搜索 - 或者根本不需要。