Drill

ProblemsJava › text

Tidy up pasted text

easytextStringsParsingJava

Text pasted from a spreadsheet arrives with tabs, newlines and runs of spaces in it. The search box wants one clean line.

normaliseSpace(text: string) → string

Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

String normaliseSpace(String text) {
    
}

Worked examples

CallResult
normaliseSpace(" hello world ")"hello world"
normaliseSpace("a\tb\nc")"a b c"
normaliseSpace("already clean")"already clean"
normaliseSpace(" ")""

Hint

Splitting on whitespace and joining with a single space does both jobs at once.

Reference solution in Java
String normaliseSpace(String text) {
    StringBuilder sb = new StringBuilder();
    for (String w : text.trim().split("\\s+")) {
        if (w.isEmpty()) continue;
        if (sb.length() > 0) sb.append(' ');
        sb.append(w);
    }
    return sb.toString();
}

The same problem in another language

More text problems in Java