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
std::string normaliseSpace(std::string text) {
}
Worked examples
| Call | Result |
|---|---|
normaliseSpace(std::string(" hello world ")) | std::string("hello world") |
normaliseSpace(std::string("a\tb\nc")) | std::string("a b c") |
normaliseSpace(std::string("already clean")) | std::string("already clean") |
normaliseSpace(std::string(" ")) | std::string("") |
Hint
Splitting on whitespace and joining with a single space does both jobs at once.
Reference solution in C++
std::string normaliseSpace(std::string text) {
istringstream in(text);
string w, result;
while (in >> w) {
if (!result.empty()) result += ' ';
result += w;
}
return result;
}