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

6

7

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?

Eades answered 6/5, 2013 at 6:45 Comment(1)
Read about StringReader: #1097121Pibroch
E
18
paragraph.substring(paragraph.lastIndexOf("\n"));
Elnora answered 6/5, 2013 at 6:50 Comment(0)
L
6
// 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);
}
Listlessness answered 6/5, 2013 at 6:49 Comment(0)
C
4

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]);
    }
Cradling answered 6/5, 2013 at 6:53 Comment(0)
S
2

you can try

paragraph.substring(paragraph.lastIndexOf("\n"));
Squarrose answered 6/5, 2013 at 6:51 Comment(2)
variable naming was a coincidence? :-)Elnora
@Elnora cheers :) and that is exisiting line in my code too :)Squarrose
K
1

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

this lastline variable would contain last line.

Kerwinn answered 6/5, 2013 at 6:51 Comment(0)
P
0

Example (slow solution)

String line = null;
Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
  line = scanner.nextLine();
}

After this line is your last line.

Pibroch answered 6/5, 2013 at 6:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.