java在第一行换行时分隔字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23756456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java separate string on first line break
提问by simon.liu
Is there any efficiency way to separate a string into two when detecting the first line break in the String
检测字符串中的第一个换行符时,是否有任何有效的方法将字符串分成两个
for example, the String like this:
例如,像这样的字符串:
String str = "line 1\n"+
"line 2\n"+
"line 3\n";
so what i want to do just separate "line 1" from the string, and the rest as another string, so finally the result as below:
所以我想要做的只是将“第 1 行”与字符串分开,其余部分作为另一个字符串,最后结果如下:
string1 = "line 1";
string2 = "line 2\n"+
"line 3\n";
采纳答案by Pshemo
You can use split(regex,limit)
method of String class. Try
您可以使用split(regex,limit)
String 类的方法。尝试
String[] result = yourString.split("\n", 2);
If you want to use OS dependent line separator
如果要使用操作系统相关的行分隔符
String[] result = yourString.split(System.lineSeparator(), 2);
or OS independent way
或操作系统独立方式
//since Java 8
String[] result = yourString.split("\R", 2);
//before Java 8
String[] result = yourString.split("\r\n|\r|\n", 2);
Now
现在
result[0] = "line 1";
result[1] = "line 2\nline 3\n";
回答by Rakesh KR
Try with String.substring()
试试 String.substring()
String str23 = "line 1 \n line 2 \n line3 \n";
String line1 = str23.substring(0, str23.indexOf("\n"));
String line2 = str23.substring(str23.indexOf("\n")+1, str23.length());
System.out.println(line1+"-----"+line2);
回答by Rafi Kamal
String str = "line 1\n line 2\n line 3\n";
int newLineIndex = str.indexOf("\n");
String first = str.substring(0, newLineIndex);
String rest = str.substring(newLineIndex + 1);