This blog is useful to all my friends who are working on the .Net Technology and wants to enhance their skills as well their problem solving ability.

Wednesday, March 7, 2012

Word Wrap function for c# (.net) ... very much useful

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;

}