tags:

views:

131

answers:

2

Is there any method in .net that wraps phrases given a maximum length for each line?

Example:

Phrase: The quick red fox jumps over the lazy cat
Length: 20

Result:

The quick red fox
jumps over the lazy
cat
+6  A: 

There is no built in method for that. You can use a regular expression:

string text = "The quick brown fox jumps over the lazy dog.";
int minLength = 1;
int maxLength = 20;
MatchCollection lines = Regex.Matches(text, "(.{"+minLength.ToString()+","+maxLength.ToString()+"})(?: |$)|([^ ]{"+maxLength.ToString()+"})");
StringBuilder builder = new StringBuilder();
foreach (Match line in lines) builder.AppendLine(line.Value);
text = builder.ToString();

Note: I corrected the pangram.

Guffa
awesome! thanks!
Schwertz
+1 Nice - but ToString() or not ToString() in the Regex? ;)
gt
@gt: If you concat strings with numbers, the numbers will be boxed and Concat(object[]) is called instead of Concat(string[]). (I missed one ToString, so I have added it.)
Guffa
A: 

The code in this article returns a list of lines, but you should be able to easily adapt it.

C# Wrapping text using split and List<>

http://bryan.reynoldslive.com/post/Wrapping-string-data.aspx

Robert Harvey