Over a million developers have joined DZone.

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

DZone's Guide to

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

Free Resource
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;


Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}