2013-05-06 113 views
0

我有一個字符串變量包含文本行從Java變量STRING的最後一行(最快的方式)

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

我requitement是讓文本的最後一行?

任何人都可以幫忙嗎?

+1

閱讀有關StringReader:http://stackoverflow.com/questions/1096621/how-to- read-a-string-line-per-line – MariuszS 2013-05-06 06:49:22

回答

7
paragraph.substring(paragraph.lastIndexOf("\n")); 
4
// 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); 
} 
0

字符串[]行= fileContents.split( 「\ n」); String lastLine = lines [lines.length - 1];

此最後一行變量將包含最後一行。

1

你可以嘗試

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

lastIndex + 1? – 2013-05-06 06:52:25

+1

變量命名是巧合? :-) – rajesh 2013-05-06 06:52:26

+1

@rajesh歡呼:)那就是我現在的代碼中的現存行:) – 2013-05-06 06:52:59

1

例(慢溶液)

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

後這條線是你的最後一道防線。

3

讓的說你的字符串是這樣

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

現在你可以使用它拆分

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