Reputation: 21
I need to remove all the spaces between letters and make the double spaces into single spaces between the words.
So this (double spaces between words):
h e l l o m y n a m e i s b o b
Will need to become this:
hello my name is bob
I've tried
temp = "h e l l o m y n a m e i s b o b"
temp = temp.trim().replaceAll("\\s", "");
but it just removes all the spaces.
I managed to make it work by doing:
temp = temp.replace(" ", ".");
temp = temp.replace(" ", "");
temp = temp.replace(".", " ");
But I would like a simpler way of doing it.
Upvotes: 2
Views: 118
Reputation: 643
You should use the regex \s(?!\s). This basically says anything that is a space but doesn't have a space after it.
This would be used like this:
temp = "h e l l o m y n a m e i s b o b";
temp = temp.replaceAll("\\s(?!\\s)", "");
System.out.println(temp);
Outputs: hello my name is bob
Hope this helps :)
Upvotes: 3
Reputation: 1231
try this
temp = temp.trim().replaceAll("(?<!\\s)\\s(?!\\s)", "");
temp = temp.replaceAll("\\s+", " ");
Upvotes: 0
Reputation: 2034
A simpler, more elegant way that does not include messing around with regex.
String yourString = "a s d d g d d d g g";
String finalstr = "";
for (String s: yourString.split(" ")) {
if (s.equals(""))
s = " ";
finalstr += s;
}
System.out.println(finalstr);
Output: asd dgddd gg
Upvotes: 0