2013-07-18 57 views
0

我想搜索特定单词的字符串,然后打印该单词之后的下5个字符。我不知道如何去做这件事。我试图寻找教程,但找不到任何东西。如何搜索一个关键字的字符串,然后在java中打印关键字后面的内容?

+0

我敢打赌,你可以做得比这更好。我敢打赌,你可以试试看,并提出一些结论。为什么不证明我是对的? –

+0

您刚刚描述了要执行此操作的算法,现在只需找到正确的方法...为您提供了一些参考:http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String。 html – fmodos

+0

我试图编写一个程序来完成这个任务,但我想不出任何东西。你能给我一些能帮助我走上正确道路的东西吗? – alexdr3437

回答

1

您可以在String上使用indexOf方法,然后为后面的字符执行substring。

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

谢谢:) :) – alexdr3437

0

您可以轻松地使用正则表达式使用MatcherPattern

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 
      } 
     } 
    } 

这个代码是找到并打印字一句后什么做到这一点。代码中的注释说明了它的工作原理。

相关问题