gpt4 book ai didi

java - 在文件中查找一个单词并在 java 中打印包含该单词的行

转载 作者:行者123 更新时间:2023-11-30 05:43:39 26 4
gpt4 key购买 nike

使用命令行,我应该输入包含文本的文件名并搜索特定单词。

foobar file.txt

我开始编写以下代码:

import java.util.*;
import java.io.*;

class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner (new File (args[1]) );
while (input.hasNext()) {
String x = input.nextLine();
}
}
}

我的程序应该找到单词,然后打印包含它的整行。请具体说明,因为我是 java 新手。

最佳答案

您已经在读取文件的每一行,因此使用 String.contains() 方法将是您的最佳解决方案

if (x.contains(word) ...

如果给定的String包含您传递给它的字符序列(或字符串),则contains()方法仅返回true

注意:此检查区分大小写,因此如果您想检查该单词是否存在任意大小写混合,只需先将字符串转换为相同的大小写即可:

if (x.toLowerCase().contains(word.toLowerCase())) ...

现在这是一个完整的示例:

public static void main(String[] args) throws FileNotFoundException {

String word = args[0];

Scanner input = new Scanner(new File(args[1]));

// Let's loop through each line of the file
while (input.hasNext()) {
String line = input.nextLine();

// Now, check if this line contains our keyword. If it does, print the line
if (line.contains(word)) {
System.out.println(line);
}
}
}

关于java - 在文件中查找一个单词并在 java 中打印包含该单词的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com