3
\$\begingroup\$

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));
\$\endgroup\$
1
  • \$\begingroup\$ I'd start by making it into a proper function I guess. Right? \$\endgroup\$ Nov 8, 2016 at 19:27

2 Answers 2

3
\$\begingroup\$

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);
}
\$\endgroup\$
0
\$\begingroup\$

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();
}
\$\endgroup\$
2
  • 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\$ Nov 9, 2016 at 2:39
  • \$\begingroup\$ Yes, deleteCharAt() make use of system.arraycopy. \$\endgroup\$ Nov 10, 2016 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.