(The story continues in A simple method for compressing white space in text (Java) - Take II.)
Intro
Now I have that text space compressor. For example,
" hello world " -> "hello world"
" \n world \t hello " -> "world hello"
Code
package io.github.coderodde.text;
import java.util.Objects;
/**
* This class provides a linear time method for compressing space
* @author Rodion "rodde" Efremov
* @version 1.0.0 (Oct 30, 2025)
* @since 1.0.0 (Oct 30, 2025)
*/
public final class TextSpaceCompressor {
public static String spaceCompress(String text) {
Objects.requireNonNull(text);
StringBuilder sb = new StringBuilder();
int textLength = text.length();
int loIndex = 0;
int hiIndex = textLength - 1;
// Scan empty prefix if any:
for (; loIndex < hiIndex; ++loIndex) {
if (!Character.isWhitespace(text.charAt(loIndex))) {
break;
}
}
// Scan empty suffix is any:
for (; hiIndex > loIndex; --hiIndex) {
if (!Character.isWhitespace(text.charAt(hiIndex))) {
break;
}
}
if (loIndex == hiIndex) {
// The input text is blank:
return "";
}
boolean scanningSpaceSequence = false;
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++;
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(spaceCompress("hello world"));
System.out.println(spaceCompress(" hello world"));
System.out.println(spaceCompress("hello world "));
System.out.println(spaceCompress(" hello \t world "));
System.out.println(spaceCompress(" cat \t \t dog \n mouse "));
}
}
Output
hello world
hello world
hello world
hello world
cat dog mouse
Critique request
As always, tell me anything that comes to mind.