To cut a string to full words you can use the following snippet.

Sample C#

public string Chop(string input, int maxLength, string chopChars="...", char spaceChar = ' ')
{
	var strings = input.Split(new[] { spaceChar }, StringSplitOptions.RemoveEmptyEntries);
	if (strings[0].Length > maxLength)
	{
		return strings[0];
	}
	var builder = new StringBuilder();
	foreach (var s in strings)
	{
		if ((builder + s).Length > maxLength)
		{
			return string.Format("{0}{1}", builder.ToString().TrimEnd(spaceChar), chopChars);
		}
		builder.Append(s + spaceChar);
	}
	return string.Format("{0}{1}", builder.ToString().TrimEnd(spaceChar), chopChars);
}

Sample VB.NET

Public Function Chop(input As String, maxLength As Integer, Optional chopChars As String = "...", Optional spaceChar As Char = " "C) As String
	Dim strings = input.Split(New () {spaceChar}, StringSplitOptions.RemoveEmptyEntries)
	If strings(0).Length > maxLength Then
		Return strings(0)
	End If
	Dim builder = New StringBuilder()
	For Each s As var In strings
		If (builder + s).Length > maxLength Then
			Return String.Format("{0}{1}", builder.ToString().TrimEnd(spaceChar), chopChars)
		End If
		builder.Append(s + spaceChar)
	Next
	Return String.Format("{0}{1}", builder.ToString().TrimEnd(spaceChar), chopChars)
End Function

One thought on “How to cut a string to full words in C# and VB.NET”

Leave a Reply