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));
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Nov 8, 2016 at 19:09
\$\endgroup\$
1
  • \$\begingroup\$ I'd start by making it into a proper function I guess. Right? \$\endgroup\$ Commented 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);
}
answered Nov 8, 2016 at 23:05
\$\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();
}
answered Nov 9, 2016 at 1:19
\$\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\$ Commented Nov 9, 2016 at 2:39
  • \$\begingroup\$ Yes, deleteCharAt() make use of system.arraycopy. \$\endgroup\$ Commented Nov 10, 2016 at 2:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.