6

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?

String
  • 3,660
  • 10
  • 43
  • 66
  • 1
    Read about StringReader: http://stackoverflow.com/questions/1096621/how-to-read-a-string-line-per-line – MariuszS May 06 '13 at 06:49

6 Answers6

16
paragraph.substring(paragraph.lastIndexOf("\n"));
rajesh
  • 3,247
  • 5
  • 31
  • 56
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);
}
jmj
  • 237,923
  • 42
  • 401
  • 438
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]);
    }
AnujMathur_07
  • 2,586
  • 2
  • 18
  • 25
2

you can try

paragraph.substring(paragraph.lastIndexOf("\n"));
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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

this lastline variable would contain last line.

Haseena
  • 53
  • 1
  • 7
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.

MariuszS
  • 30,646
  • 12
  • 114
  • 155