Nguyen Nghi Nguyen Nghi - 2 months ago 8
Java Question

Spilt sentence to array of words keep fomat

I wanna spilt a sentence to a array of words
e.g.

Hello this a sentence
this is a new line


I used
String[] arr = String.spilt(str)

but when i wanna combine array to sentence the result is:

Hello this a sentence this is a new line


So how i can split string keep new line characters?
Thank you!

Answer

Split takes regular expression,

split("(?=\n)")

This will preserve the \n

Provided your string contains \n

public static void main(String[] arg){
    String str= "Hello this a sentence \n this is a new line";
    System.out.println(str);
    String[] xyz = str.split("(?=\n)");
    System.out.println(Arrays.toString(xyz));
}
Comments