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
C# 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
public 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 C#
public string NormaliseSpace(string text) {
var parts = text.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries);
return string.Join(" ", parts);
}