Schwertz
Schwertz

Reputation: 1073

Wrap phrases in .NET

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

Upvotes: 4

Views: 364

Answers (2)

Guffa
Guffa

Reputation: 700582

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.

Upvotes: 7

Robert Harvey
Robert Harvey

Reputation: 180858

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

Upvotes: 0

Related Questions