[英]Printing words from text file
我現在有這個程序,它運行一個 txt 文件並打印文件中以 A 或 T 開頭的行。現在我正在努力讓它只打印以一個結尾的單詞,或; 有人認為他們可以幫助我嗎?
這是我的程序
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) throws IOException {
Scanner sf = new Scanner(new File("amazing.txt"));
List<String> text = new ArrayList<>();
while (sf.hasNextLine()) {
String current = sf.nextLine();
if (current.startsWith("T") || current.startsWith("A")) {
System.out.println(current);
}
}
sf.close();
}
}
使用String#endsWith
嗎?
while (sf.hasNextLine()) {
String current = sf.nextLine();
if (current.endsWith(",") || current.endsWith(";"))
System.out.println(current);
}
稍微復雜一點的解決方案可能是使用正則表達式匹配來執行此檢查:
while (sf.hasNextLine()) {
String current = sf.nextLine();
if (current.matches(".*[,;]\\s*"))
System.out.println(current);
}
這將檢查每一行是否以逗號或分號結尾,之后可能帶有一些空格。
@TimBiegeleisen已經提供了一個很好的答案。
為了完整起見,讓我還提供一個基於流的解決方案,該解決方案使用NIO (Javas newer,modern File API),它正在使用他的檢查:
Files.lines(Path.of("amazing.txt"))
.filter(line -> line.matches(".*[,;]\\s*"))
.forEach(System.out::println);
由於Path.of
,該代碼至少需要 Java 11 。 或者 Java 8 如果您使用Paths.get("amazing.txt")
代替。
如果您打算將這些行添加到text
而不是打印它們,您可以輕松修改代碼:
Files.lines(Path.of("amazing.txt"))
.filter(line -> line.matches(".*[,;]\\s*"))
.forEach(text::add);
或者讓 stream 自己創建列表,那么您不必這樣做:
List<String> text = Files.lines(Path.of("amazing.txt"))
.filter(line -> line.matches(".*[,;]\\s*"))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.