Tidy up pasted text
Text pasted from a spreadsheet arrives with tabs, newlines and runs of spaces in it. The search box wants one clean line.
- Every run of whitespace becomes a single space.
- No leading or trailing space is left.
- Text that is nothing but whitespace comes back empty.
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.
Where you start
String normaliseSpace(String text) {
}
Worked examples
| Call | Result |
|---|---|
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();
}