Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last n lines (sentences) in a String in Java

I am looking for an efficient way to remove last n lines from a String. Efficient as in- fast performing as well as something that does not create too may objects. Therefore would like to stay away from split(). Especially because, at times, my strings could be a few hundred or even thousand lines.

For instance, I am getting a string as such:

This is a sample code line 1.
This is a sample code line 2.

Warm Regards,
SomeUser.

The last 3 lines (an empty line, "Warm Regards,", and "SomeUser.") is what I am trying to get rid of. Note that the content (including the last 3 lines) isn't fixed.

I am thinking of counting the lines first using this solution here: https://stackoverflow.com/a/18816371/1353174 and then again, use another similar loop to reach to a position that is lines - n and do a substring till that position.

However, just posting this problem here to know if there are any other and perhaps more efficient ways to achieve this. External library-based solutions (like Apache Commons StringUtils) are also welcome.

like image 873
kpatil Avatar asked Mar 29 '26 18:03

kpatil


1 Answers

You can use String.lastIndexOf to find last third occurrence of '\n' symbol and then do String.substring to get the result.

     public static void main(String[] args) {
        String s = "This is a sample code line 1.\n" +
                "This is a sample code line 2.\n" +
                "\n" +
                "Warm Regards,\n" +
                "SomeUser.";

        int truncateIndex = s.length();

        for (int i = 0; i < 3; i++) {
            System.out.println(truncateIndex);
            truncateIndex = s.lastIndexOf('\n', truncateIndex - 1);
        }

        System.out.println(s.substring(0, truncateIndex));
        System.out.println("--");
    }

This code snippet intentionally doesn't care for corner cases, such as when there is less than three lines in input string, to make code simple and readable.

like image 110
Aivean Avatar answered Mar 31 '26 10:03

Aivean