打印包含我们模式的单词和位置

Print the word that contains our pattern with the position

我试着用位置打印包含我们模式的单词。我尝试使用布尔变量来检查文本是否匹配,如果匹配则打印,但它不起作用。如何打印带有位置的文本?

如果string pat在string text中,则打印已经找到的索引,打印包含String pat的单词。比如est在testing里面,所以我们要打印testing这个词。

当前输出

Pattern found at index 20
Pattern found at index 49
Pattern found at index 89

想要输出

Pattern found at index 20 in-word testing
Pattern found at index 49 in-word test
Pattern found at index 89 in-word est's
    public class FindWord {

    public static void search(String txt, String pat)
    {
        int M = pat.length();
        int N = txt.length();
        //boolean found = false;

        for (int i = 0; i <= N - M; i++) {

            int j;

            for (j = 0; j < M; j++)
                if (txt.charAt(i + j) != pat.charAt(j))
                    break;

            if (j == M)
               // found = true;
                System.out.println("Pattern found at index " + i);
//                if(found)
//                    System.out.println(txt.charAt(i));
        }
    }

    public static void main(String[] args)
    {
        String txt = "This is only for a testing input. +\n" +
                     "This is for testing, example input.+\n" +
                     "We want to find est's index and print text";
        String pat = "est";
        search(txt, pat);
    }
} 

不太明白你的问题:如果在String txt中找到索引和String pat,是否要打印?

if (j == M) {
    System.out.printf("Pattern found at index %d in-word %s%n", i, pat);
}

此外,您可以使用 indexOf() 方法来达到目标​​。看看 Java 字符串:https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)

if (j == M)
{
    String s = "";
    for(int k = i; txt.charAt(k) != ' ' && k >= 0; k--) s = txt.charAt(k) + s;
              
    for(int k = i + 1; txt.charAt(k) != ' ' && k < txt.length(); k++) s += txt.charAt(k);
              
    System.out.println("Pattern found at index " + i + ", " + s);
}

类似这样,但您需要修改一些细节以使其无错误。

据我了解,您想打印找到子字符串的整个单词。您可以通过在找到的字符串的左侧和右侧搜索 space 个字符来提取该词,如下所示:

if (j == M) {
    // searching for a space to the left of the string
    int leftSpace = i;
    while (leftSpace > 0 && txt.charAt(leftSpace) != ' ') {
        leftSpace--;
    }

    // searching for a space to the right of the string
    int rightSpace = i + j;
    while (rightSpace < txt.length() && txt.charAt(rightSpace) != ' ') {
        rightSpace++;
    }

    // corner-case where the pattern is at the beginning of the text
    if (leftSpace != 0) {
        leftSpace++;
    }

    String word = txt.substring(leftSpace, rightSpace);

    System.out.println("Pattern found at index " + i + " in-word " + word);
}

可以用lastIndexOfindexOf得到space的索引,得到单词

  if (j == M){
      int s = txt.lastIndexOf(' ', i) + 1;
      int e = txt.indexOf(' ', i);
      if(e == -1) e = N;
      System.out.println("Pattern found at index " + i +" "+ txt.substring(s, e));
  }