Accommodating legacy database tables that were designed specifically for the IBM mainframe screens they represent has caused me much aggravation. Often, I find the need to break a string into multiple lines to fit the table column width as well as the users who are still viewing the data with terminal emulators. Here are two functions I've written to perform that task, accepting a string and a line width as parameters and returning some string enumerable. Which do you think is the better function and why? And by all means share the super-easy-fast-efficient way that I totally overlooked.
public string[] BreakStringIntoArray(string s, int lineWidth)
{
int lineCount = ((s.Length + lineWidth) - 1) / lineWidth;
string[] strArray = new string[lineCount];
for (int i = 0; i <= lineCount - 1; i++)
{
if (((i * lineWidth) + lineWidth) >= s.Length)
strArray[i] = s.Substring(i * lineWidth);
else
strArray[i] = s.Substring(i * lineWidth, lineWidth);
}
return strArray;
}
vs.
public List<string> BreakStringIntoList(string s, int lineWidth)
{
List<string> lines = new List<string>();
if (s.Length > lineWidth)
{
lines.Add(s.Substring(0, lineWidth));
lines.AddRange(this.BreakStringIntoList(s.Substring(lineWidth), lineWidth));
}
else
{
lines.Add(s);
}
return lines;
}
For example, passing in ("Hello world", 5)
would return 3 strings:
"Hello"
" worl"
"d"