Reputation: 11
I want to basically to do this:
String secondString = firstString.trim().replaceAll(" +", " ");
Or replace all the multiple spaces in my string, with just a single space. However, is it possibly to do this without regex like I am doing here?
Thanks!
Upvotes: 1
Views: 468
Reputation: 201447
However, is it possibly to do this without regex like I am doing here?
Yes. The regular expression is clear and easy to read, so I would probably use that; but you could use a nested loop, a StringBuilder
and Character.isWhitespace(char)
like
StringBuilder sb = new StringBuilder();
for (int i = 0; i < firstString.length(); i++) {
sb.append(firstString.charAt(i));
if (Character.isWhitespace(firstString.charAt(i))) {
// The current character is white space, skip characters until
// the next character is not.
while (i + 1 < firstString.length()
&& Character.isWhitespace(firstString.charAt(i + 1))) {
i++;
}
}
}
String secondString = sb.toString();
Note: This is a rare example of a nested loop that is O(N); the inner loop modifies the same counter as the outer loop.
Upvotes: 1