有没有一种方法可以在 Java 中使用 indexOf 在单个解析中查找给定文本中多个字符串的位置?
例如,我想在一次解析文本“你今天能参加会议吗?”中为“you”和“meeting”做一个 indexOf。
任何帮助将不胜感激!提前致谢
当您提出问题时:不。
但是,您可以使用带有匹配项的正则表达式 string.matches(".*(meeting|today).*")。有关正则表达式的语法,请参见 javadoc。如果您只使用字母和数字,您可以从示例中构造模式,但有些字符需要用 \ 引用,在这样的文字中会变成 \。
如果您要在文本中搜索某些模式,请使用正则表达式。在您的情况下,如果您想在给定的文本中找到一些字符串,我会编写一个基本函数:
public static void main(String ... args) {
String a = "i have a little dog";
String [] b = new String [] { "have", "dog" };
locateStrings(a,b);
}
public static int [] locateStrings(String source, String [] str) {
if (source == null || str == null || str.length == 0)
throw new IllegalArgumentException();
int [] result = new int [str.length];
for (int i = 0; i < str.length ; i++) {
result[i] = source.indexOf(str[i]);
}
return result;
}