【发布时间】:2010-11-10 18:35:48
【问题描述】:
我有以下代码(继承!),它将一行文本分成两行,并带有 html 换行符<br/>。
public static string BreakLineIntoTwo(this HtmlHelper helper, string input)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
if (input.Length < 12) return input;
int pos = input.Length / 2;
while ((pos < input.Length) && (input[pos] != ' '))
pos++;
if (pos >= input.Length) return input;
return input.Substring(0, pos) + "<br/>" + input.Substring(pos + 1);
}
规则似乎是如果文本行少于 12 个字符,则返回它。如果没有找到文本的中间并移动到下一个空格并插入换行符。我们也可以假设结尾没有双空格和额外的空格,并且文本不仅仅是一长行字母abcdefghijkilmnopqrstuvwxyz等。
这似乎工作正常,我的问题是Is there a more elegant approach to this problem?
【问题讨论】:
-
string.Replace("\n", "<br />")有什么问题吗? -
@Mehrdad - 我的文本中没有要替换的 \n。
-
我想你正在尝试在 html 端实现这一点。如果你将文本放入具有自动换行 css 属性的容器中,当文本长度小于容器?
-
@Myra - 我对此持开放态度,愿意分享一个显示示例的链接吗?
-
不知道你想在哪里使用这个方法。如果它的唯一功能是将文本匹配到显示区域,那么使用 CSS 会更好。
标签: c#