Do you want to wrap a string to a desired width for printing or other purposes, then here is a small snippet.
<code>
public static List<string> StringWrap(string srcStr, int maxWidth)
{
List<string> lstLines = new List<string>();
int spcCount = 0;
if (!string.IsNullOrEmpty(srcStr))
{
string[] Lines = srcStr.Split(new char[] { '\n', '\r' });
foreach (string Line in Lines)
{
string[] Words = Line.Split(' ');
string curLine = "";
foreach (var word in Words)
{
spcCount = (curLine.Length > 0 ? 1 : 0);
if (curLine.Length + word.Length + spcCount > maxWidth && !string.IsNullOrEmpty(curLine))
{
lstLines.Add(curLine.PadRight(maxWidth));
curLine = "";
}
if (word.Length <= maxWidth)
{
if (string.IsNullOrEmpty(curLine))
curLine = word;
else
curLine += " " + word;
}
else
{
if (!string.IsNullOrEmpty(curLine))
{
lstLines.Add(curLine.PadRight(maxWidth));
curLine = "";
}
for (int j = 0; j < word.Length; j += maxWidth)
{
if (j + maxWidth < word.Length)
lstLines.Add(word.Substring(j, maxWidth));
else
lstLines.Add(word.Substring(j).PadRight(maxWidth));
}
}
}
if (!string.IsNullOrEmpty(curLine))
{
lstLines.Add(curLine.PadRight(maxWidth));
}
}
}
return lstLines;
}
</code>
Any modification or suggestion on this is highly appreciated.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.