IC Improve Code Recipes

Recipe 15.6 · C#

String Helpers: Truncate, Slugify, Mask

Problem

Three small string jobs come up in almost every business app. Text must be cut to fit a column or a grid cell. Titles must become URL-friendly slugs. Account numbers and e-mail addresses must be masked in logs, screens and e-mails. The homegrown versions break on short input, accented characters and emoji, or reveal more than they hide.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: crashes, mangles and leaks.
public static string Truncate(string s, int len)
{
    return s.Substring(0, len) + "...";   // crashes if shorter
}

public static string MakeUrl(string title)
{
    return title.ToLower().Replace(" ", "-")
        .Replace("&", "").Replace("'", "");  // "Crème" stays
}

public static string MaskCard(string card)
{
    return "XXXX-XXXX-XXXX-" + card.Substring(12);
}

The improved recipe

C#
using System;
using System.Globalization;
using System.Text;

namespace ImproveCode.Utilities;

public static class TextHelpers
{
    public static string Truncate(
        string? value, int maxLength, string ellipsis = "...")
    {
        ArgumentOutOfRangeException.ThrowIfNegative(maxLength);
        if (string.IsNullOrEmpty(value) || value.Length <= maxLength)
        {
            return value ?? string.Empty;
        }

        if (maxLength <= ellipsis.Length)
        {
            return Cut(value, maxLength);
        }

        return Cut(value, maxLength - ellipsis.Length).TrimEnd()
            + ellipsis;
    }

    public static string Slugify(string? text, int maxLength = 80)
    {
        if (string.IsNullOrWhiteSpace(text))
        {
            return string.Empty;
        }

        string decomposed = text.Normalize(NormalizationForm.FormD);
        var slug = new StringBuilder(decomposed.Length);
        bool pendingDash = false;

        foreach (char c in decomposed)
        {
            if (CharUnicodeInfo.GetUnicodeCategory(c)
                == UnicodeCategory.NonSpacingMark)
            {
                continue;
            }

            if (!char.IsAsciiLetterOrDigit(c))
            {
                pendingDash = slug.Length > 0;
                continue;
            }

            int needed = pendingDash ? 2 : 1;
            if (slug.Length + needed > maxLength)
            {
                break;
            }

            if (pendingDash)
            {
                slug.Append('-');
                pendingDash = false;
            }

            slug.Append(char.ToLowerInvariant(c));
        }

        return slug.ToString();
    }

    public static string Mask(
        string? value, int visibleAtEnd = 4, char maskChar = '*')
    {
        if (string.IsNullOrEmpty(value))
        {
            return string.Empty;
        }

        // Never reveal more than half of the value.
        int visible = Math.Clamp(visibleAtEnd, 0, value.Length / 2);
        return new string(maskChar, value.Length - visible)
            + value[^visible..];
    }

    public static string MaskEmail(string? email)
    {
        if (string.IsNullOrWhiteSpace(email))
        {
            return string.Empty;
        }

        int at = email.IndexOf('@');
        if (at <= 0)
        {
            return Mask(email, 0);
        }

        return email[0] + "***" + email[at..];
    }

    private static string Cut(string value, int length)
    {
        if (length > 0 && char.IsHighSurrogate(value[length - 1]))
        {
            length--;
        }

        return value[..length];
    }
}

Usage snippet:

C#
TextHelpers.Truncate("Quarterly compliance report", 15);
// "Quarterly co..."
TextHelpers.Slugify("Crème Brûlée & Co.: 2026 Menu!");
// "creme-brulee-co-2026-menu"
TextHelpers.Mask("4111111111111111");   // "************1111"
TextHelpers.MaskEmail("pat.lee@example.com"); // "p***@example.com"

How it works

Truncate returns short input unchanged, never returns null, and counts the ellipsis inside the limit, so a 50-character column really gets at most 50 characters. Cut steps back one position if the cut would split a surrogate pair, which otherwise leaves half a character that turns into a replacement character once the text is encoded as UTF-8.

Slugify decomposes the text with Unicode normalization form D, which splits é into e plus a combining accent, and then drops the accents. Only ASCII letters and digits survive; every run of anything else becomes a single dash, and leading and trailing dashes never appear. The length limit is checked before each append, so the slug never ends in a dash after being cut.

Mask shows at most the last few characters and never more than half of the value, so a short value is not fully exposed by a default meant for card numbers. MaskEmail shows the first character and the domain and always uses three stars, so the mask doesn't reveal the length of the name.

Variations and pitfalls

  • Some letters don't decompose: ß, æ, ø and ł are dropped by Slugify. If your content uses them, add a small replacement table (ß to ss, æ to ae) before the loop.
  • Slugs for non-Latin titles come out empty. Fall back to the record ID, and store the slug once rather than recomputing it, so links don't break when a title is edited.
  • Truncate counts UTF-16 code units. For text with emoji or combining marks shown to users, cut on text elements with StringInfo instead. For database columns, code units are what nvarchar(n) counts, so the simple version is correct.
  • Masking is for display. Logs should not receive the full value at all, masked afterwards or not. See Chapter 4.
  • Slugify builds its result in a StringBuilder, not with += in the loop. About 16,471 files in the archive append to a string with += "...", in 33 engagements. Inside a loop that copies the whole string on every pass; for a handful of pieces it doesn't matter, for a few thousand rows it does.