My solution
To separate the words and keep the multiple blank spaces
String[] words = str.split(" ");
And to attach use the following function:
public static String join(String r[],String d) {
if (r.length == 0) return "";
StringBuilder sb = new StringBuilder();
int i;
for(i=0;i<r.length-1;i++)
sb.append(r[i]).append(d);
return sb.toString()+r[i];
}
Your use
String str = join(words, " ");
The tests I have done, regards the initial chain.
Update
Solution based on the response of @Leonbloy
String str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit\n Fusce erat mau[ris], pretium sed metus in, efficitur\n\nultima.";
To separate the words, taking into account, tabulators and line breaks.
String[] list = str.split("((?<=\s)(?!\s))|((?<!\s)(?=\s))");
To attach the String array to a String
StringBuilder builder = new StringBuilder();
for(String s : list) {
builder.append(s);
}
String endStr = builder.toString();
System.out.println(endStr);