Java 如何在字符串中打印子字符串的所有实例
所以,我现在有一个文件,我正在尝试使用一个命令来搜索文本中包含我要查找的内容的所有行 以下是我目前掌握的情况:Java 如何在字符串中打印子字符串的所有实例,java,string,file,substring,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();
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有一只猫”和“Bob有一只狗”
所以我不知道在while循环中放什么。我知道您必须使用indexOf 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);
}
}
如果您想要更详细的内容,例如获取给定行中查询匹配项的所有索引,那么您应该尝试使用Pattern
和Matcher
():
将打印:
Chris has a cat
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
和快乐编码插入文件读取
干杯 为什么需要indexOf?如果您不关心单词边界,您可以执行string.contains。另外,您确定要在扫描的文件内容之前有一个空行吗?因此,只需在每一行上循环,并打印出包含给定单词的行。请至少自己努力找出它。发布所有不适用的代码并要求我们做实际的工作并不是一个学习东西的好方法。我们很乐意帮忙,但你至少应该试着做点什么。一个空的while
循环,这里是什么?这不是努力。感谢您的编辑,现在和您期望的相比,它产生了什么样的输出?
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