【问题标题】:How to print all instances of a substring in a string如何打印字符串中子字符串的所有实例
【发布时间】:2017-12-08 00:51:09
【问题描述】:

所以,我目前有一个文件,我正在尝试使用一个命令来搜索该文本中包含我要查找的内容的所有行。

这是我目前所拥有的:

public class finder
{
   public static void main(String args[]) throws FileNotFoundException
   {
       Scanner console = new Scanner (System.in);

       String search = console.nextLine();
       Scanner s = new Scanner(new File("C:\\Users\\xxxxx\\Desktop\\test.txt"));

       while (s.hasNextLine())
       {
         String temp = s.nextLine();
         if (temp.contains(search))
         {
            System.out.println(temp);
         }
       }
   } //Main

} //Finder

文字是这样的

Bob has a cat
Bob has a dog
Chris has a cat

如果我搜索“猫”,它会打印出“鲍勃有一只猫”和“克里斯有一只猫”。 如果我搜索“Bob”,它会打印出“Bob has a cat”和“Bob has a dog”。

所以我不知道在 while 循环中放什么。我知道你必须对 indexOf 字符串命令做一些事情,但我不确定如何实现它。

【问题讨论】:

  • 为什么需要 indexOf?如果你不关心单词边界,你可以做 string.contains
  • 另外,您确定要在扫描的文件内容前有一个空行吗?
  • 所以只需遍历每一行并打印出包含给定单词的行。
  • 请至少自己努力弄清楚。发布所有不适用的代码并要求我们做实际工作并不是学习东西的好方法。我们很乐意提供帮助,但您至少应该尝试做一些事情。一个空的while 循环和这里发生了什么?不是努力。
  • 感谢您的编辑,与您的预期相比,现在产生的输出是什么?

标签: java string file substring


【解决方案1】:

如果您只想匹配整行,只需在给定的 String 行上调用 contains 以过滤您想要的:

import java.util.Arrays;
import java.util.List;

public class TestSearch {
    public static void main(String[] args) {
        String query = "chris";
        List<String> dataList = Arrays.asList("Bob has a cat", "Bob has a dog", "Chris has a cat");
        dataList.stream().filter(str -> str.toLowerCase().contains(query)).forEach(System.out::println);
    }
}

将打印:

Chris has a cat

如果您想要更详细的信息,例如在给定行中获取查询匹配项的所有索引,那么您应该尝试使用 PatternMatcher (pretty good tutorial here):

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestPattern {
    public static void main(String[] args) {
        String query = "bob";
        System.out.println("Searching for \"" + query + "\"...");
        Pattern patt = Pattern.compile(query);
        Arrays.asList(
                "Bob has a cat bob", 
                "Bob has a dog", 
                "Chris has a cat",
            "Cat has a chris that is a bob")
        .forEach(line -> {
            System.out.println("Checking in line = \"" + line + "\"");
            Matcher matcher = patt.matcher(line.toLowerCase());
            while (matcher.find()) {
                System.out.println("found! index = " + matcher.start());
            }
        });
    }
}

将打印:

Searching for "bob"...
Checking in line = "Bob has a cat bob"
found! index = 0
found! index = 14
Checking in line = "Bob has a dog"
found! index = 0
Checking in line = "Chris has a cat"
Checking in line = "Cat has a chris that is a bob"
found! index = 26

使用java.nio 插入您的文件阅读并快乐编码!

干杯!

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2011-09-29
    相关资源
    最近更新 更多