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

public string Slugify(string title) {
    
}

Worked examples

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

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#
public string Slugify(string title) {
    var sb = new StringBuilder();
    foreach (char ch in title.ToLowerInvariant()) {
        if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) sb.Append(ch);
        else if (sb.Length > 0 && sb[sb.Length - 1] != '-') sb.Append('-');
    }
    if (sb.Length > 0 && sb[sb.Length - 1] == '-') sb.Length--;
    return sb.ToString();
}

The same problem in another language

More text problems in C#