java中怎么实现在一个字符串中查找其中的关键字。

我需要查的关键字不只是一个,是很多个啊。。

public class $ {

public static void main(String... _) {

String str = "123456789 abcdefg hijklmn...";

System.out.println(str.indexOf("456"));
System.out.println(str.indexOf("45a"));
}
}

结果:
3
-1

如果有,就返回他的起始位置,注意是从0开始
没有,就返回-1

用循环

String[] key = { "456", "abc", "45a" };
String str = "123456789 abcdefg hijklmn...";

for (int i = 0; i < key.length; i++) {
System.out.println(key[i] + "的起始位置:" + str.indexOf(key[i]));
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-05-22
用正则

------------------------------------------------------------------
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Cmd {

public static void main(String[] args) {
String str = "abcdaskdfa;2328382";
Pattern p = Pattern.compile("232");
Matcher m = p.matcher(str);
while(m.find()){
if(!"".equals(m.group())){
System.out.println(m.group());
}
}
}
}
第2个回答  2012-05-26
变量.indexof("所查找的关键字")
第3个回答  2012-05-23
indexof方法!