c-sharp

Truncate String Without Word Break

Truncate string at a word near to the limit specified. Avoid word split.

Abhith Rajan
Abhith RajanSeptember 14, 2020 · 1 min read · Last Updated:
/// <summary>
/// Truncate string at a word near to the limit specified. Avoid word split.
/// </summary>
/// <param name="input">string</param>
/// <param name="length"></param>
/// <param name="appendDots"></param>
/// <returns></returns>
public static string TruncateAtWord(this string input, int length, bool appendDots = false)
{
    if (input == null || input.Length < length)
        return input;
    var iNextSpace = input.LastIndexOf(" ", length, StringComparison.Ordinal);
    var trimmedInput = string.Format("{0}", input.Substring(0, (iNextSpace > 0) ? iNextSpace : length).Trim());

    if (appendDots)
    {
        return trimmedInput + "...";
    }
    return trimmedInput;
}

Tests

[Fact]
public void TruncateAtWordTests()
{
    "This is a long sentence".TruncateAtWord(6).Should().Be("This");
    "This is a long sentence".TruncateAtWord(7).Should().Be("This is");
}

Reference

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Abhith Rajan

Written byAbhith Rajan
Abhith Rajan is a software engineer by day and a full-stack developer by night. He's coding for almost a decade now. He codes 🧑‍💻, write ✍️, learn 📖 and advocate 👍.
Connect

Is this page helpful?

Related ArticlesView All

Related VideosView All

C# Project Management in VS Code [Pt 3] | C# and .NET Development in VS Code for Beginners

Installing VS Code and C# Dev Kit [Pt 2] | C# and .NET Development in VS Code for Beginners

What is VS Code and C# Dev Kit? [Pt 1] | C# and .NET Development in VS Code for Beginners