java string split based on new line -
i have following string
string str="aaaaaaaaa\n\n\nbbbbbbbbbbb\n \n";
i want break on \n
@ end should 2 string aaaaaaaa
, bbbbbbbb
. dont want last 1 contain white space. if split based on new line character using str.split()
final array should have 2 entry only.
i tried below:
string str="aaaaaaaaa\n\n\nbbbbbbbbbbb\n \n".replaceall("\\s+", " "); string[] split = str.split("\n+");
it ignore \n
, give single string aaaaaaaaaa bbbbbbbb
.
delete call replaceall()
, removing newlines too. do:
string[] split = str.split("\n\\s*");
this not split on spaces - split must start @ newline (followed optional further whitespace).
here's test code using sample input edge case enhancement:
string str = "aaaaaaaaa\nbbbbbb bbbbb\n \n"; string[] split = str.split("\n\\s*"); system.out.println(arrays.tostring(split));
output:
[aaaaaaaaa, bbbbbb bbbbb]
Comments
Post a Comment