Avión Avión - 5 days ago 5
Java Question

Get the string until a line break, and the rest of it on another variable in Java

I'm trying to get the first paragraph of a text (until a line break) on a variable, and the rest thing in another variable.

For example for a text like:


hello how are you im really fine thank you, and you, im fine. thanks a
lot good bye.

foo bar random text foo bar random text foo bar random
text foo bar random text foo bar random text .
blahblahblah
blahblahblah blahblahblah blahblahblah blahblahblah blahblahblah.


My aim is to get on

String firstpart = "hello how are you im really fine thank you, and you, im fine. thanks a lot good bye."
String restofit = "foo bar random text foo bar random text foo bar random text foo bar random text foo bar random text \n lahblahblah blahblahblah blahblahblah blahblahblah blahblahblah blahblahblah."


This is my try:

String[] result = mytext.split("\n", 2);
System.out.println(result[0]);
if (result[1] != null) System.out.println("nas");


But I'm getting
java.lang.ArrayIndexOutOfBoundsException: 1
on the
result[1]
line (maybe not with the text of the example, but with my real text), when the input string is only composed by one line.

Is my approach correct? How can I fix the error?

Thanks in advance.

Answer

You need to escape the backslash:

String[] result = mytext.split("\\R",2);
//check length of result:
if(result.length >1){
    //do what you need with result[1];
}

Java turns a double backslash \\ in a string into one backslash in runtime. This is because of special characters such as ",'.

Comments