5

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:

string1 = "line 1";
string2 = "line 2\n"+
          "line 3\n";
Pshemo
  • 122,468
  • 25
  • 185
  • 269
simon.liu
  • 117
  • 1
  • 2
  • 10

3 Answers3

22

You can use split(regex,limit) method of String class. Try

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";
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • MacOS uses `\r` as line separator, please fix regex with `\r|\n|\r\n` – Dmitry Ginzburg May 20 '14 at 10:01
  • @DmitryGinzburg you are right about need to include Mac separator but your regex would not work as expected because it would create two splits on `\r\n`, one for `\r` and one for `\n` because regex is interpreted from left to right. That is why `\r\n` should be before `\r` and `\n`. Anyway thanks for pointing that out. – Pshemo May 20 '14 at 10:07
  • it's likely you're right, the correct regex would be `\r|\n|(\r\n)`. Or just `(\r?\n)|\r` – Dmitry Ginzburg May 20 '14 at 10:09
  • 1
    @DmitryGinzburg What I meant is that regex such as `foo|bar|foobar` will never match `foobar` because it will earlier search for `foo` or `bar` which will consume parts for `foobar`. General rule is to place more detailed regexes in `regex1|regex2|regex3` before more general ones. That is why `\r\n` should be placed before `\r` and `\n` like in regex from my answer. "Or just `\r?\n|\r`" yes, this one will work correctly. – Pshemo May 20 '14 at 10:12
6

Try with 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);
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
4
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);
Rafi Kamal
  • 4,522
  • 8
  • 36
  • 50