如何在字符串中搜索关键字,然后在java中打印该关键字后面的内容?

如何在字符串中搜索关键字,然后在java中打印该关键字后面的内容?,java,string,search,Java,String,Search,我想在字符串中搜索一个特定的单词,然后打印该单词后面的5个字符。我不知道该怎么办。我已尝试搜索教程,但找不到任何内容。您可以对字符串使用indexOf方法,然后对后面的字符执行子字符串 int start = yourString.indexOf(searchString); System.out.println(yourString.subString(start + 1, start + 6); 使用Matcher和Pattern import java.util.regex.*; //i

我想在字符串中搜索一个特定的单词,然后打印该单词后面的5个字符。我不知道该怎么办。我已尝试搜索教程,但找不到任何内容。

您可以对字符串使用indexOf方法,然后对后面的字符执行子字符串

int start = yourString.indexOf(searchString);
System.out.println(yourString.subString(start + 1, start + 6);

使用
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
            }
        }
    }
import java.util.regex.*//进口
公共类stringAfterString{//类声明
公共静态void main(字符串[]args){//main方法

Pattern=Pattern.compile(“(?我打赌你可以做得更好。我打赌你可以尝试一下,然后想出一些接近的东西。为什么不证明我是对的?你刚才描述了做这件事的算法,现在只要找到正确的方法……给你一些参考:我试着写一个程序来完成这件事,但我想不出任何东西。你能给我一些东西吗“这将有助于我走上正确的道路?”alexdr3437查看我的答案。