Word Wrap function for c# (.net)

Most of the technical posts I make on this blog, are issues that I struggle with for a day or two, and was unable to find a good solution for on the internet. Once I find the solution, I try to post it here, to try and make things easier on everyone else out there.  I made a similar post to usenet microsoft.public.dotnet.faqs group last April, about doing word wrap in .net.  This weekend, someone sent some feedback from my blog asking if that post was mine, and thanking me for the information. I really appreciated the comment, since it is hard to tell if people out there need and use the information I post.

In any case, I decided to repost the word wrap function to my blog, in hopes that more people can get some use out of it.

 

public static string[] Wrap(string text, int maxLength)

{

text = text.Replace("\n", " ");

text = text.Replace("\r", " ");

text = text.Replace(".", ". ");

text = text.Replace(">", "> ");

text = text.Replace("\t", " ");

text = text.Replace(",", ", ");

text = text.Replace(";", "; ");

text = text.Replace("
"
, " ");

text = text.Replace(" ", " ");

 

string[] Words = text.Split(' ');

int currentLineLength = 0;

ArrayList Lines = new ArrayList(text.Length / maxLength);

string currentLine = "";

bool InTag = false;

 

foreach (string currentWord in Words)

{

//ignore html

if (currentWord.Length > 0)

{

 

if (currentWord.Substring(0,1) == "<")

InTag = true;

 

if (InTag)

{

//handle filenames inside html tags

if (currentLine.EndsWith("."))

{

currentLine += currentWord;

 

}

 

else

currentLine += " " + currentWord;

if (currentWord.IndexOf(">") > -1)

InTag = false;

 

}

 

else

{

if (currentLineLength + currentWord.Length + 1 < maxLength)

{

currentLine += " " + currentWord;

currentLineLength += (currentWord.Length + 1);

}

 

else

{

Lines.Add(currentLine);

currentLine = currentWord;

currentLineLength = currentWord.Length;

 

}

}

}

}

 

if (currentLine != "")

Lines.Add(currentLine);

string[] textLinesStr = new string[Lines.Count];

Lines.CopyTo(textLinesStr, 0);

return textLinesStr;

}

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
Print | posted on Monday, January 23, 2006 5:42 AM

Feedback

# re: Word Wrap function for c# (.net)

left by adriana at 10/3/2007 1:09 AM Gravatar
hello jason!
nice blog..
btw how to remove integer in string ya?
i mean i want to return string only..

# re: Word Wrap function for c# (.net)

left by David Somuah at 7/2/2008 4:45 PM Gravatar
This is great thanks for this. I was about to write a wrap function myself, you have saved me a lot of time.

# re: Word Wrap function for c# (.net)

left by Goran at 9/28/2008 1:54 PM Gravatar
This blog was very useful for me, thanks :)

# re: Word Wrap function for c# (.net)

left by codebounce.com at 10/4/2008 2:28 PM Gravatar
Excellent post and useful.
Added to my bookmarks:

http://www.codebounce.com/ASPNET

# re: Word Wrap function for c# (.net)

left by Vincent Courcelle at 10/23/2008 11:42 AM Gravatar
hello,

there is a fastest way to do the same:

/// <summary>
/// Properly cuts the string on a white space and append appendWhenCut when cutted.
/// </summary>
/// <param name="me"></param>
/// <param name="appendWhenCut"></param>
/// <param name="maxLength"></param>
/// <returns></returns>
public static string SubstringWordCut(this string me,string appendWhenCut,uint maxLength)
{
if(me.Length>maxLength)
{
me=me.Substring(0,(int)maxLength-appendWhenCut.Length);
char[] cutPossible=new char[] { ' ',',','.','?','!',':',';','-','\n','\r','\t' };
int cutIndex=me.LastIndexOfAny(cutPossible);
if(cutIndex>0)
{ return me.Substring(0,cutIndex).Trim()+appendWhenCut; }
else
{ return me+appendWhenCut; }
}
return me;
}

# re: Word Wrap function for c# (.net)

left by Max Black at 5/17/2009 2:31 PM Gravatar
I modified Vincent courcelle's code, to make it work for my app.


[blockquote] public string Wrap(string me, uint maxLength)
{
string com = "";
for (int i = 1; i < ((int)(me.Length / maxLength) + 1); i++)
{
if (me.Length / i > maxLength)
{
string m = me.Substring((int)(i * maxLength), (int)maxLength);
char[] cutPossible = new char[] { ' ', ',', '.', '?', '!', ':', ';', '-', '\n', '\r', '\t' };
int cutIndex = m.LastIndexOfAny(cutPossible);
if (cutIndex > 0)
{ com += m.Substring(0, cutIndex).Trim() + Environment.NewLine; }
else
{ com += m + Environment.NewLine; }
}
else
{
return com;
}
}
return "";
}
[/blockquote]

# re: Word Wrap function for c# (.net)

left by kathy at 9/5/2009 10:23 AM Gravatar
Hi Jason,
Thanks for your work. I have a question.When I try to wrap a textbox to a certain lenght and insert linebreaks when the length is reached all I get it is;
System.String[]. Would you please tell me what am I doing wrong?

thx,
kathy

# Using regex.

left by MV11 at 11/24/2009 9:07 AM Gravatar
static string Wrap(string text, int max)
{
return Regex.Replace(text, @"(^| +)([^\r\n]{0," + max + @"}(?![\w\p{P}]))", "$2\r\n", RegexOptions.Multiline);
}

# re: Word Wrap function for c# (.net)

left by vinaykumar at 2/26/2010 3:35 PM Gravatar
hi,

i am using a repeater to show the data.I like to show the inserted paragraghs data to be displayed as paragraphs.I am trying but was not able to get ................Please reply be as soon as possible

# re: Word Wrap function for c# (.net)

left by Daniel at 3/19/2010 9:00 PM Gravatar
How this works, an example please!

example: Wrap(blah blah, blah blah)

# re: Word Wrap function for c# (.net)

left by Johan Andersson at 11/2/2010 10:55 PM Gravatar
Hi!
Thanks for sharing all the code snippets. However I did not succeeds using any of them, but they were a good starting point.
I've posted my solution with unit tests here:
http://johan.andersson.net/2010/11/03/wordwrap-function-in-c/

Regards,
Johan Andersson

# re: Word Wrap function for c# (.net)

left by W at 11/30/2010 11:31 AM Gravatar
none worked for me...I'll have to go for another method :\

# re: Word Wrap function for c# (.net)

left by kavi at 4/27/2011 11:38 PM Gravatar
i can able to wrap a text in ie7 but thats not happening in ie8

# re: Word Wrap function for c# (.net)

left by kieran at 7/22/2011 2:53 AM Gravatar
think you need to add some notes withing this document, this will help a beginner c# programmer, in which I believe they are the main readers of this document

# Use MX11's RegEx version!

left by Hoss at 1/11/2012 5:46 PM Gravatar
I tried every example here and by far the best one with was MV11's. The only issue I had with his RegEx version was when the input strnig contain new lines, it would double the new line in the output.

I'm not a RegEx guy, so here's yet another solution for word wrapping that seems to work very well for me no matter what I throw at it. It based on MV11's RegEx example...

static string Wrap1(string text, int max)
{
string[] inputLines = text.Replace("\r",string.Empty).Split('\n');
StringBuilder output = new StringBuilder();

foreach (string x in inputLines)
{
output.Append(Regex.Replace(x, @"(^| +)([^\n]{0," + max + @"}(?![\w\p{P}]))", "$2" + Environment.NewLine, RegexOptions.Multiline));
}

return output.ToString();
}
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: