DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Arthur has posted 13 posts at DZone. View Full User Profile

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

  • submit to reddit
        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)

		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;