How to print the log line containing a specific date from a text block in Java

1 Answer

0 votes
public class FindLogByDate {

    public static void printLogByDate(String logs, String targetDate) {
        String[] lines = logs.split("\n");

        for (String line : lines) {
            if (line.contains(targetDate)) {
                System.out.println(line);
                return; // stop after first match
            }
        }

        System.out.println("Date not found.");
    }

    public static void main(String[] args) {
        String logs =
            "01/12/2023 - Log entry one.\n" +
            "17/03/2021 - Log entry two.\n" +
            "29/07/2019 - Log entry three.\n" +
            "05/11/2024 - Log entry four.\n" +
            "22/08/2020 - Log entry five.\n" +
            "14/02/2018 - Log entry six.\n" +
            "30/09/2022 - Log entry seven.\n" +
            "11/06/2017 - Log entry eight.\n" +
            "03/04/2025 - Log entry nine.\n" +
            "26/01/2016 - Log entry ten.\n";

        printLogByDate(logs, "05/11/2024");
    }
}



/*
run:

05/11/2024 - Log entry four.

*/

 



answered 11 hours ago by avibootz

Related questions

...