我想在字符串中搜索特定单词,然后在该单词后面打印接下来的5个字符。我不知道该怎么做。我试过搜索教程但找不到任何东西。
答案 0 :(得分:1)
您可以在String上使用indexOf方法,然后为之后的字符执行子字符串。
int start = yourString.indexOf(searchString);
System.out.println(yourString.subString(start + 1, start + 6);
答案 1 :(得分: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
}
}
}
此代码在单词句子之后查找并打印任何内容。代码中的注释解释了它的工作原理。