[英]java getting Last line(fastest way) from a String Variable
我有一个字符串变量,包含文本行
line1(Contains String)
line2(Contains String)
line3(Contains String)
line4(Contains String)
我的要求是得到文本的最后一行?
有谁可以帮忙吗?
paragraph.substring(paragraph.lastIndexOf("\n"));
// 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);
}
假设您的字符串是这样的
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]);
}
String []行= fileContents.split(“ \\ n”); 字符串lastLine = lines [lines.length-1];
该lastline变量将包含最后一行。
你可以试试
paragraph.substring(paragraph.lastIndexOf("\n"));
示例(慢速解决方案)
String line = null;
Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
}
该行之后是您的最后一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.