Over a million developers have joined DZone.

C#: Break Long Strings Of Text That Don't Contain A Space

·
Long strings of text with no spaces breaks most tables since the browser doesn't know where to start a new line. This function breaks a string after a number of characters so that they can be properly displayed in tables


// Put this at the top
using System.Text.RegularExpressions;
//

public string BreakLongString(string SubjectString, int CharsToBreakAfter)
{
	string Pattern = "\\S{" + CharsToBreakAfter + ",}";
	int Counter = 0;
	bool IsMatching = Regex.IsMatch(SubjectString, Pattern);
	while (IsMatching)
	{

		Counter++;
		string MatchedString = Regex.Match(SubjectString, Pattern).Value;
		SubjectString = SubjectString.Replace(MatchedString.Substring(0, (CharsToBreakAfter - 1)), MatchedString.Substring(0, (CharsToBreakAfter - 1)) + " ");

		// Prevent endless loops
		if (Counter > 20) break;

		// Check if we still have long strings
		IsMatching = Regex.IsMatch(SubjectString, Pattern);
	}

	return SubjectString;
}

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}