我想在字符串中搜索特定单词,然后在该单词之后打印接下来的 5 个字符。我不知道该怎么做。我曾尝试搜索教程,但找不到任何东西。
问问题
126 次
2 回答
1
您可以对字符串使用 indexOf 方法,然后对后面的字符进行子字符串处理。
int start = yourString.indexOf(searchString);
System.out.println(yourString.subString(start + 1, start + 6);
于 2013-07-18T23:34:04.103 回答
0
Matcher
您可以使用和使用正则表达式轻松完成此操作Pattern
import java.util.regex.*; //import
public class stringAfterString { //class declaration
public static void main(String [] args) { //main method
Pattern pattern = Pattern.compile("(?<=sentence).*"); //regular expression, matches anything after sentence
Matcher matcher = pattern.matcher("Some lame sentence that is awesome!"); //match it to this sentence
boolean found = false;
while (matcher.find()) { //if it is found
System.out.println("I found the text: " + matcher.group().toString()); //print it
found = true;
}
if (!found) { //if not
System.out.println("I didn't find the text."); //say it wasn't found
}
}
}
此代码在单词 sentence 之后查找并打印任何内容。代码中的注释解释了它是如何工作的。
于 2013-07-18T23:37:06.163 回答