Thank you for the code. I found that whenever there is words that are longer than max width, it causes bugs. Therefore, I have done the following correction to enable the words to be splited into seperate lines:
private static string[] BreakLines(string originalText, int maxWidth) {
string[] textWords;
textWords= originalText.Split(' ');
// Handler first string longer than maxwidth scenario
if (textWords.Length == 1 & textWords[0].Length > maxWidth)
{
int remainder=textWords[0].Length % maxWidth;
int lnBreaked = textWords[0].Length / maxWidth;
if (remainder >0)
lnBreaked = lnBreaked + 1;
textWords = new string[lnBreaked];
for (int x = 0; x < textWords.Length ; x++)
{
int curIdx = x * maxWidth + maxWidth +1;
if (curIdx <= originalText.Length)
textWords[x] = originalText.Substring(x * maxWidth, maxWidth);
else
textWords[x] = originalText.Substring(x * maxWidth, originalText.Length - (x * maxWidth));
}
}
int wordIndex = 0;
string tmpLine = "";
ArrayList textLines = new ArrayList();
while (wordIndex < textWords.Length){
if (textWords[wordIndex] == "") { wordIndex++; }
else
{
string backupLine = tmpLine;
if (tmpLine == "") { tmpLine = textWords[wordIndex]; }
else{ tmpLine = tmpLine + " " + textWords[wordIndex]; }
if (tmpLine.Length <= maxWidth)
{
wordIndex++;
// If our line is still small enough, but we don't have anymore words
// add the line to the collection
if (wordIndex == textWords.Length) { textLines.Add(tmpLine); }
}
else
{
// If current word is longer than maxwidth
if (tmpLine.Contains(" ") == false && tmpLine.Length > maxWidth)
{
int remainder=tmpLine.Length % maxWidth;
int lnBreaked = tmpLine.Length / maxWidth;
if (remainder > 0)
lnBreaked = lnBreaked + 1;
string[] strTmp = new String[lnBreaked];
for (int x = 0; x < strTmp.Length; x++)
{
int curIdx = x * maxWidth + maxWidth + 1;
if (curIdx <= tmpLine.Length)
{
strTmp[x] = tmpLine.Substring(x * maxWidth, maxWidth);
}
else
{
strTmp[x] = tmpLine.Substring(x * maxWidth, tmpLine.Length - (x * maxWidth));
}
}
foreach (string s in strTmp)
{
textLines.Add(s);
}
wordIndex++;
tmpLine = "";
}
else
{
// Our line is too long, add the previous line to the collection
// and reset the line, the word causing the 'overflow' will be
// the first word of the new line
textLines.Add(backupLine);
tmpLine = "";
}
}
}
}
string[] textLinesStr = new string[textLines.Count];
textLines.CopyTo(textLinesStr, 0);
return textLinesStr;
} /* BreakLines */
Enter your message below
Sign in or Join us (it's free).