java getting Last line(fastest way) from a String Variable

12,068

Solution 1

paragraph.substring(paragraph.lastIndexOf("\n"));

Solution 2

// get the index of last new line character
int startIndex = str.lastIndexOf("\n");

String result = null;

// see if its valid index then just substring it to the end from that

if(startIndex!=-1 && startIndex!= str.length()){
  str.subString(startIndex+1);
}

Solution 3

let say your string is like this

String s = "aaaaaaaaaaaaa \n bbbbbbbbbbbbbbb \n cccccccccccccccccc \nddddddddddddddddddd";

Now you can split it using

    String[] arr = s.split("\n");
    if (arr != null) {
        // get last line using : arr[arr.length - 1]
        System.out.println("Last    =====     " + arr[arr.length - 1]);
    }

Solution 4

String[] lines = fileContents.split("\n"); String lastLine = lines[lines.length - 1];

this lastline variable would contain last line.

Solution 5

you can try

paragraph.substring(paragraph.lastIndexOf("\n"));
Share:
12,068
String
Author by

String

Updated on June 04, 2022

Comments

  • String
    String almost 2 years

    I have a String Variable Contains lines of text

    line1(Contains String)
    line2(Contains String)
    line3(Contains String)
    line4(Contains String)
    

    My requitement is to get a Last line of text?

    Could any one help?