Truncate String Without Word Break

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

commit 5ba4a07 · authored · 1 min read

/// <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

local graph · open full graph

"Truncate String Without Word Break" is connected to the topics C# and related to 7 other entries. NDepend - The Best-in-class Static Code Analyzer for Dotnet NDepend - The Best-in-class… C# - Convert DateTime to Long and Vice Versa C# - Convert DateTime to Lo… C# - Get Last N characters from a string C# - Get Last N characters … C# - Get Web.Config Connection String in a Class Library C# - Get Web.Config Connect… Using AutoMapper in a .NET Core Class Library Using AutoMapper in a .NET … Check if string is Arabic - C# Check if string is Arabic -… Mask String Mask String C# #c-sharp Truncate String Without Word Break

comments

loading discussion…