patternjavaMinor
Removing extra spaces without using a regular expression
Viewed 0 times
expressionwithoutremovingregularspacesusingextra
Problem
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?
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));Solution
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.
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);
}Code Snippets
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);
}Context
StackExchange Code Review Q#146517, answer score: 3
Revisions (0)
No revisions yet.