2 回答

TA貢獻1934條經(jīng)驗 獲得超2個贊
您已經(jīng)在讀取文件的每一行,因此使用該方法將是您的最佳解決方案String.contains()
if (x.contains(word) ...
如果給定的包含您傳遞給它的字符序列(或字符串),則該方法只是返回。contains()trueString
注意:此檢查區(qū)分大小寫,因此,如果要檢查該單詞是否存在任何大小寫組合,只需先將字符串轉(zhuǎn)換為相同的大小寫:
if (x.toLowerCase().contains(word.toLowerCase())) ...
所以現(xiàn)在這里有一個完整的例子:
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);
}
}
}

TA貢獻1851條經(jīng)驗 獲得超4個贊
首先,您必須打開文件,然后逐行讀取它,并檢查該單詞是否在該行中。
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0]; // the word you want to find
try (BufferedReader br = new BufferedReader(new FileReader("foobar.txt"))) { // open file foobar.txt
String line;
while ((line = br.readLine()) != null) { //read file line by line in a loop
if(line.contains(word)) { // check if line contain that word then prints the line
System.out.println(line);
}
}
}
}
}
添加回答
舉報