这取决于stringArray 是什么。如果是Collection 那就没问题了。如果它是一个真正的数组,您应该将其设为Collection。 Collection 接口有一个名为contains() 的方法,它将确定给定的Object 是否在Collection 中。
将数组转换为Collection的简单方法:
String tokens[] = { ... }
List<String> list = Arrays.asList(tokens);
List 的问题是查找成本很高(技术上是线性的或O(n))。更好的选择是使用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
}
您可能希望更有效地执行此操作(例如不编译每一行的模式),但这是使用的基本工具。