I want to remove the extra spaces without using a regular expression. I'm using two while loops.
How can this become better / more elegant?
String str = "Hola caracola ";
char[] src = str.toCharArray(), dest = new char[src.length];
int i = 0, j = 0;
while (i < src.length - 1) {
while (i < src.length - 1 && src[i] == ' ' && src[i + 1] == ' ') {
i++;
}
dest[j++] = src[i++];
}
System.out.println(new String(dest, 0, j));
-
\$\begingroup\$ I'd start by making it into a proper function I guess. Right? \$\endgroup\$Mathieu Guindon– Mathieu Guindon2016年11月08日 19:27:45 +00:00Commented Nov 8, 2016 at 19:27
2 Answers 2
Your code is buggy: it fails to copy the last character.
As @Mat'sMug says, defining a function would be a good idea.
The task can be done with one array and one loop.
public static String compressConsecutiveSpaces(String str) {
if (str.isEmpty()) return str;
char[] chars = str.toCharArray();
int dest = 1;
for (int src = 1; src < chars.length; src++) {
if (!(chars[src - 1] == ' ' && chars[src] == ' ')) {
chars[dest++] = chars[src];
}
}
return new String(chars, 0, dest);
}
I just took the OCA for Java 7SE and there were a lot of questions about StringBuilder, so using that was my first inclination. The answer using a char array might be quicker, but the code below seems pretty clear and straightforward as an alternative.
public static String removeDoubleSpaces(String str)
{
StringBuilder sb = new StringBuilder(str);
int dblSpaceLoc;
while (0 <= dblSpaceLoc = sb.indexOf(" "))
{
sb.deleteCharAt(dblSpaceLoc);
}
// if also wish to remove leading/trailing spaces:
// return sb.toString().trim();
return sb.toString();
}
-
2\$\begingroup\$ Note that
StringBuilder.deleteCharAt()
would cause all of the subsequent characters to be immediately copied over to fill the gap. For long strings, doing multiple.deleteCharAt()
operations would be a performance problem. \$\endgroup\$200_success– 200_success2016年11月09日 02:39:08 +00:00Commented Nov 9, 2016 at 2:39 -
\$\begingroup\$ Yes, deleteCharAt() make use of system.arraycopy. \$\endgroup\$Phil Freihofner– Phil Freihofner2016年11月10日 02:02:40 +00:00Commented Nov 10, 2016 at 2:02