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());1415 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}