简体   繁体   中英

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM