Geeks With Blogs

News
Jason Coyne Jason Coyne's blog

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;

}

Posted on Monday, January 23, 2006 5:42 AM Programming , c# | Back to top


Comments on this post: Word Wrap function for c# (.net)

# re: Word Wrap function for c# (.net)
Requesting Gravatar...
hello jason!
nice blog..
btw how to remove integer in string ya?
i mean i want to return string only..

Left by adriana on Oct 03, 2007 1:09 AM

# re: Word Wrap function for c# (.net)
Requesting Gravatar...
This is great thanks for this. I was about to write a wrap function myself, you have saved me a lot of time.
Left by David Somuah on Jul 02, 2008 4:45 PM

# re: Word Wrap function for c# (.net)
Requesting Gravatar...
This blog was very useful for me, thanks :)
Left by Goran on Sep 28, 2008 1:54 PM

# re: Word Wrap function for c# (.net)
Requesting Gravatar...
Excellent post and useful.
Added to my bookmarks:

http://www.codebounce.com/ASPNET
Left by codebounce.com on Oct 04, 2008 2:28 PM

# re: Word Wrap function for c# (.net)
Requesting 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;
}
Left by Vincent Courcelle on Oct 23, 2008 11:42 AM

# re: Word Wrap function for c# (.net)
Requesting 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]
Left by Max Black on May 17, 2009 2:31 PM

# re: Word Wrap function for c# (.net)
Requesting 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
Left by kathy on Sep 05, 2009 10:23 AM

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

# re: Word Wrap function for c# (.net)
Requesting 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
Left by vinaykumar on Feb 26, 2010 3:35 PM

# re: Word Wrap function for c# (.net)
Requesting Gravatar...
How this works, an example please!

example: Wrap(blah blah, blah blah)
Left by Daniel on Mar 19, 2010 9:00 PM

# re: Word Wrap function for c# (.net)
Requesting 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
Left by Johan Andersson on Nov 02, 2010 10:55 PM

# re: Word Wrap function for c# (.net)
Requesting Gravatar...
none worked for me...I'll have to go for another method :\
Left by W on Nov 30, 2010 11:31 AM

# re: Word Wrap function for c# (.net)
Requesting Gravatar...
i can able to wrap a text in ie7 but thats not happening in ie8
Left by kavi on Apr 27, 2011 11:38 PM

# re: Word Wrap function for c# (.net)
Requesting 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
Left by kieran on Jul 22, 2011 2:53 AM

# Use MX11's RegEx version!
Requesting 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();
}
Left by Hoss on Jan 11, 2012 5:46 PM

# re: Word Wrap function for c# (.net)
Requesting Gravatar...
Thanks. useful.
Left by Abolfazl BEigi on Sep 22, 2012 1:43 AM

Your comment:
 (will show your gravatar)


Copyright © Jason Coyne | Powered by: GeeksWithBlogs.net | Join free