【发布时间】:2010-09-09 20:33:10
【问题描述】:
我现在有一个可行的解决方案,但对于如此(看似)简单的事情来说,它似乎真的很难看。
我尝试在添加单词超过中间标记时打破它,在添加单词之前和之后都分裂,但根据单词的长度,它可能会在第一行或第二行不平衡。
在复杂修复之前我最初遇到问题的示例输入:
输入"Macaroni Cheese"和"Cheese Macaroni"
应该分别输出"Macaroni<br/> Cheese"和"Cheese<br/> Macaroni"。
但更简单的解决方案要么适用于第一个,但不能适用于第二个,或者反过来。
这就是我所拥有的,但我想知道是否有更优雅的方式来做到这一点。
public string Get2LineDisplayText(string original)
{
string[] words = original.Split(new[] {' ', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
//Degenerate case with only 1 word
if (words.Length <= 1)
{
return original;
}
StringBuilder builder = new StringBuilder();
builder.Append(words[0]); //Add first word without prepending space
bool addedBr = false;
foreach (string word in words.Skip(1))
{
if (builder.Length + word.Length < original.Length / 2) //Word fits on the first line without passing halfway mark
{
builder.Append(' ' + word);
}
else if (!addedBr) //Adding word goes over half, need to see if it's more balanced on the 1st or 2nd line
{
int diffOnLine1 = Math.Abs((builder.Length + word.Length) - (original.Length - builder.Length - word.Length));
int diffOnLine2 = Math.Abs((builder.Length) - (original.Length - builder.Length));
if (diffOnLine1 < diffOnLine2)
{
builder.Append(' ' + word);
builder.Append("<br/>");
}
else
{
builder.Append("<br/>");
builder.Append(' ' + word);
}
addedBr = true;
}
else //Past halfway and already added linebreak, just append
{
builder.Append(' ' + word);
}
}
return builder.ToString();
}
示例输入/输出:
【问题讨论】:
-
您能否提供一些(简短的)示例输入和预期输出?
-
@Jeff 以前有,但现在更清楚了。
-
+1 给所有人,但接受了最容易理解的那个。