Drill

ProblemsC++ › text

Turn a product title into a URL slug

mediumtextStringsParsingC++

The catalogue builds a URL from each product title, and the result has to be safe to put in a path.

slugify(title: 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 slugify(std::string title) {
    
}

Worked examples

CallResult
slugify(std::string(" Blue Widget, 12mm! "))std::string("blue-widget-12mm")
slugify(std::string("A---B"))std::string("a-b")
slugify(std::string("Already-slugged"))std::string("already-slugged")
slugify(std::string("!!!"))std::string("")

Hint

Append a dash only when there is already something to separate, then trim the one you may have left on the end.

Reference solution in C++
std::string slugify(std::string title) {
    string result;
    for (char raw : title) {
        char ch = static_cast<char>(tolower(static_cast<unsigned char>(raw)));
        if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) result += ch;
        else if (!result.empty() && result.back() != '-') result += '-';
    }
    if (!result.empty() && result.back() == '-') result.pop_back();
    return result;
}

The same problem in another language

More text problems in C++