Removing extra spaces without using a regular expression 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 &lt; src.length - 1) {
    while (i &lt; src.length - 1 &amp;&amp; src[i] == ' ' &amp;&amp; src[i + 1] == ' ') {
        i++;
    }
    dest[j++] = src[i++];
}

System.out.println(new String(dest, 0, j));
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 &lt; chars.length; src++) {
        if (!(chars[src - 1] == ' ' &amp;&amp; chars[src] == ' ')) {
            chars[dest++] = chars[src];
        }
    }
    return new String(chars, 0, dest);
}