Collapse Whitespace Runs In Text

Strip edges and collapse whitespace runs with \s+ into single spaces before equality or dedup checks, noting which characters \s does not cover.

JavaData Integrity

Code

snippet
public class WhitespaceNormalizer {

    // \s 只匹配六个 ASCII 空白字符(space/tab/LF/VT/FF/CR),NBSP 不在其中
    static String normalize(String input) {
        return input.strip().replaceAll("\\s+", " ");
    }

    public static void main(String[] args) {
        String raw = "  balance\tupdating   finished \n";
        System.out.println("[" + raw + "]");
        System.out.println("[" + normalize(raw) + "]");

        // 归一化让仅空白不同的字符串可以相等比较与去重
        System.out.println(normalize("a  b").equals("a b"));
    }
}

How it works

The code’s whole job belongs to the class WhitespaceNormalizer and the functions normalize and main.

Watch out for

  • Every symbol it touches is a language built-in — nothing to fetch.

Using it

Signature: static String normalize(String input)

Launch the file; main takes over and steps through normalize.

Key statements

return input.strip().replaceAll("\\s+", " ");

Interactive Tools for This Topic

FAQ

How do you run Collapse Whitespace Runs In Text?
It runs as-is — treat the file as the whole program and execute it.