I made this method that takes any string and transforms it into a multiline text l; each line having the max (character) length specified by the rowLength
parameter.
How can I make this better, functionality and code wise?
There is currently one known issue. It sometimes adds an empty line at the end because I have to add the Enviroment.NewLine
call. Check it out, please, and give some suggestions.
public static string ConvertToMultiLineText(string value, int rowLength)
{
var multiLine = new StringBuilder();
string[] lines = value.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var filterLines = lines.Where(line => !line.IsNullEmptyOrWhiteSpace());
foreach (var line in filterLines)
{
if (line.IsNullEmptyOrWhiteSpace())
continue;
if (line.Length > rowLength)
{
int startIndex = 0;
var number = (decimal)line.Length / rowLength;
var rowNumber = Math.Ceiling(number);
for (int i = 0; i < rowNumber; i++)
{
if (line.Contains(@" "))
{
int lastIndex = rowLength;
// if it's not the first row set the last character on the current row of the iteration
if (i != 0)
lastIndex = (rowLength * (i + 1));
// if it's the last row set last character as the lenght of the last row
if (i == rowNumber - 1)
lastIndex = line.Length - 1;
int lastSpace = line.LastIndexOf(@" ", lastIndex, StringComparison.Ordinal);
//if " " is found inside the string
if (lastSpace > -1)
{
var lastOccurence = (lastSpace <= startIndex) ? startIndex - lastSpace : lastSpace - startIndex;
if (i == rowNumber - 1)
multiLine.Append(line.Substring(startIndex, lastOccurence) + Environment.NewLine + line.Substring(lastSpace, line.Length - lastSpace));
else
multiLine.Append(line.Substring(startIndex, lastOccurence) + Environment.NewLine);
startIndex = lastSpace;
}
else
{
if (i == rowNumber - 1)
multiLine.Append(line.Substring(startIndex, (line.Length - rowLength * ((int)rowNumber - 1))));
else
multiLine.Append(line.Substring(startIndex, rowLength) + Environment.NewLine);
startIndex += rowLength;
}
}
else
{
if (i == rowNumber - 1)
multiLine.Append(line.Substring(startIndex, (line.Length - rowLength * ((int)rowNumber - 1))));
else
multiLine.Append(line.Substring(startIndex, rowLength) + Environment.NewLine);
startIndex += rowLength;
}
}
}
else
multiLine.Append(line.Substring(0, line.Length) + Environment.NewLine);
}
return string.Format(@"{0}", multiLine);
}