Simplicity
It strikes me that the simplest method to do this is to leverage the standard library. You will want to learn how to use regular expressions. Your effort will be rewarded.
public final class TextSpaceCompressor {
public static String spaceCompress(String text) {
return text.strip().replaceAll("\\s+", " ");
}
}
Now, this will also remove newlines. Your test examples indicate you're okay doing this, but if you wanted to preserve newlines you could use streams to map over the lines, perform the substitutions and then collect the string back together, joining with newlines.
import java.util.stream.Collectors;
public final class TextSpaceCompressor {
public static String spaceCompress(String text) {
return text
.lines()
.map(line -> line.strip().replaceAll("\\s+", " "))
.collect(Collectors.joining("\n"));
}
}
You might further wish to remove empty lines. For instance, "hello world \n foo \n \n bar" becoming "hello world\nfoo\nbar".
import java.util.stream.Collectors;
public final class TextSpaceCompressor {
public static String spaceCompress(String text) {
return text
.lines()
.map(line -> line.strip().replaceAll("\\s+", " "))
.filter(line -> line != "")
.collect(Collectors.joining("\n"));
}
}
Comments on your code
I note this loop:
while (loIndex <= hiIndex) { char ch = text.charAt(loIndex); if (!Character.isWhitespace(ch)) { sb.append(ch); scanningSpaceSequence = false; } else if (!scanningSpaceSequence) { scanningSpaceSequence = true; sb.append(' '); } loIndex++; }
- You have some inconsistent whitespace.
- In either branch of the conditional you set the value of
scanningSpaceSequencebut you do it in one case before appending to your string buffer, and in one case after. The order doesn't matter, so it feels odd that this is not consistent. - Since the increment of
loIndexis not conditional, this might be better suited to a for loop.
for (; loIndex <= hiIndex; loIndex++) {
char ch = text.charAt(loIndex);
if (!Character.isWhitespace(ch)) {
sb.append(ch);
scanningSpaceSequence = false;
} else if (!scanningSpaceSequence) {
sb.append(' ');
scanningSpaceSequence = true;
}
}
In your main method, it would be a good idea to create an array of strings, and then iterate over them. This will greatly facilitate adding test cases.
public static void main(String[] args) {
String[] tests = {
"hello world",
" hello world",
"hello world ",
" hello \t world ",
" cat \t \t dog \n mouse "
};
for (String test : tests) {
System.out.println(spaceCompress(test));
}
}