Drill

ProblemsC++ › text

Tidy up pasted text

easytextStringsParsingC++

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

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.

Solve it in Python →

Where you start

std::string normaliseSpace(std::string text) {
    
}

Worked examples

CallResult
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;
}

The same problem in another language

More text problems in C++