c-sharp

Truncate String Without Word Break

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

Edson Frainlar
Edson FrainlarSeptember 14, 2020 · 1 min read · Last Updated:
1/// <summary>
2/// Truncate string at a word near to the limit specified. Avoid word split.
3/// </summary>
4/// <param name="input">string</param>
5/// <param name="length"></param>
6/// <param name="appendDots"></param>
7/// <returns></returns>
8public static string TruncateAtWord(this string input, int length, bool appendDots = false)
9{
10 if (input == null || input.Length < length)
11 return input;
12 var iNextSpace = input.LastIndexOf(" ", length, StringComparison.Ordinal);
13 var trimmedInput = string.Format("{0}", input.Substring(0, (iNextSpace > 0) ? iNextSpace : length).Trim());
14
15 if (appendDots)
16 {
17 return trimmedInput + "...";
18 }
19 return trimmedInput;
20}

Tests

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

Reference

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


Edson Frainlar

Written byEdson Frainlar
Mission-driven Full-stack Developer with a passion for developing KTern, Dev Collaboration, and teaching. Curious to explore Quantum Information and Computing.
Connect

Is this page helpful?

Related VideosView All

Don't Use AutoMapper in C#! Do THIS Instead!

How slow is MediatR really?

C# Language Highlights: Properties