c-sharp

Truncate String Without Word Break

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

Abhith RajanSeptember 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

Written by Abhith Rajan
Abhith Rajan is an aspiring software engineer with more than 8 years of experience and proven successful track record of delivering technology-based products and services.
Buy me a coffee

Was this helpful?

👈 This is a live react editor.

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

Related StoriesView All