简体   繁体   中英

Printing words from text file

I have this program right now that runs a txt file and prints the lines from the file that start with A or T. Now I am tying to make it so that it will just print the words that end with an, or; Anyone think they could help me?

Here is my program rn

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(); 
    }
}

Use String#endsWith ?

while (sf.hasNextLine()) {
    String current = sf.nextLine(); 
    if (current.endsWith(",") || current.endsWith(";"))
        System.out.println(current);
}

A slightly more sophisticated solution might be to use regex matching to do this check:

while (sf.hasNextLine()) {
    String current = sf.nextLine(); 
    if (current.matches(".*[,;]\\s*"))
        System.out.println(current);
}

This would check that each line ends in comma or semicolon, possibly with some whitespace afterward.

@TimBiegeleisen already provided a great answer.

For completeness, let me also provide a stream-based solution that uses NIO (Javas newer, modern File API) which is using his check:

Files.lines(Path.of("amazing.txt"))
    .filter(line -> line.matches(".*[,;]\\s*"))
    .forEach(System.out::println);

The code requires at least Java 11 because of Path.of . Or Java 8 if you use Paths.get("amazing.txt") instead.


In case you intended to add those lines to text instead of printing them, you can easily modify the code:

Files.lines(Path.of("amazing.txt"))
    .filter(line -> line.matches(".*[,;]\\s*"))
    .forEach(text::add);

Or let the stream create the list itself, then you do not have to do it:

List<String> text = Files.lines(Path.of("amazing.txt"))
    .filter(line -> line.matches(".*[,;]\\s*"))
    .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM