这取决于是什么stringArray
。如果是的Collection
话就好了。如果它是一个真正的数组,则应将其设为Collection
. 该Collection
接口有一个调用方法,该方法contains()
将确定给定Object
对象是否在Collection
.
将数组转换为 的简单方法Collection
:
String tokens[] = { ... }
List<String> list = Arrays.asList(tokens);
a 的问题List
是查找很昂贵(技术上是线性的或O(n)
)。更好的选择是使用 a Set
,它是无序的,但具有近乎恒定的 ( O(1)
) 查找。您可以像这样构建一个:
从一个Collection
:
Set<String> set = new HashSet<String>(stringList);
从数组:
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
然后set.contains(line)
将是一个廉价的操作。
编辑:好的,我认为你的问题不清楚。您想查看该行是否包含数组中的任何单词。你想要的是这样的:
BufferedReader in = null;
Set<String> words = ... // construct this as per above
try {
in = ...
while ((String line = in.readLine()) != null) {
for (String word : words) {
if (line.contains(word)) [
// do whatever
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) { try { in.close(); } catch (Exception e) { } }
}
这是一个相当粗略的检查,它的使用出奇地开放,并且往往会在诸如“废品”之类的词上给出令人讨厌的误报。对于更复杂的解决方案,您可能必须使用正则表达式并查找单词边界:
Pattern p = Pattern.compile("(?<=\\b)" + word + "(?=\b)");
Matcher m = p.matcher(line);
if (m.find() {
// word found
}
您可能希望更有效地执行此操作(例如不编译每一行的模式),但这是使用的基本工具。