【发布时间】:2010-12-06 09:37:37
【问题描述】:
容纳专门为它们所代表的 IBM 大型机屏幕设计的遗留数据库表让我非常恼火。通常,我发现需要将字符串分成多行以适应表格列宽以及仍在使用终端模拟器查看数据的用户。这是我为执行该任务而编写的两个函数,接受字符串和线宽作为参数并返回一些可枚举的字符串。您认为哪个功能更好,为什么?并通过各种方式分享我完全忽略的超级简单快速高效的方式。
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;
}
对比
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;
}
例如,传入 ("Hello world", 5) 将返回 3 个字符串:
"Hello"
" worl"
"d"
【问题讨论】: