如何在字符串中打印子字符串的所有实例

时间:2017-12-08 00:51:10

标签: java string file substring

所以,我目前有一个文件,我正在尝试使用一个命令搜索该文本中我正在寻找的所有行。

这是我到目前为止所拥有的:

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

如果我搜索“cat”,它会打印出“Bob有一只猫”,“Chris有一只猫”。 如果我搜索“Bob”,它将打印出“Bob有一只猫”,“Bob有一只狗”。

所以我不知道在while循环中放什么。我知道你必须使用indexOf string命令做一些事情,但我不知道如何实现它。

1 个答案:

答案 0 :(得分:0)

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

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

如果您想要更精细的内容,例如在给定的行中获取查询匹配的所有索引,那么您应该尝试使用PatternMatcherpretty 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插入文件阅读并快乐编码!

干杯!