【问题标题】:split a line of text into two lines using a <br> in c#在c#中使用<br>将一行文本分成两行
【发布时间】:2010-11-10 18:35:48
【问题描述】:

我有以下代码(继承!),它将一行文本分成两行,并带有 html 换行符&lt;br/&gt;

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", "&lt;br /&gt;") 有什么问题吗?
  • @Mehrdad - 我的文本中没有要替换的 \n。
  • 我想你正在尝试在 html 端实现这一点。如果你将文本放入具有自动换行 css 属性的容器中,当文本长度小于容器?
  • @Myra - 我对此持开放态度,愿意分享一个显示示例的链接吗?
  • 不知道你想在哪里使用这个方法。如果它的唯一功能是将文本匹配到显示区域,那么使用 CSS 会更好。

标签: c#


【解决方案1】:

可能的改进将是类似于

private const MinimumLengthForBreak = 12;
private const LineBreakString = "<br />";

public static string BreakLineIntoTwo(this HtmlHelper helper, string input)
{
    if (string.IsNullOrEmpty(input)) return string.Empty;
    if (input.Length < MinimumLengthForBreak ) return input;

    int pos = input.IndexOf(' ', input.Length / 2);
    if (pos < 0) return input; // No space found, not checked in original code

    return input.Substring(0, pos) + LineBreakString + input.Substring(pos + 1);
}

注意:由于我在工作,无法检查 atm,因此未检查语法。

【讨论】:

    【解决方案2】:

    您可以使用IndexOf 而不是自己循环遍历字符串。

    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;
    
        pos = input.IndexOf(' ', pos);
    
        return input.Substring(0, pos) + "<br/>" + input.Substring(pos + 1);
    }
    

    【讨论】:

    • 这不会检查IndexOf是否找不到字符,因此它不会与原始代码相同。
    【解决方案3】:

    为什么不使用 word-wrap 的 css 属性。

    通过 word-wrap 属性,你可以通过指定 break-word 来强制长文本换行。

    查看example

    最好的问候
    迈拉

    【讨论】:

    【解决方案4】:

    使用 'IndexOf' 和 'Insert' 的较短版本:

        private string BreakLineIntoTwo(string input)
        {
            if (string.IsNullOrEmpty(input)) return string.Empty;
            if (input.Length < 12) return input;          
    
           int index = input.IndexOf(" ", input.Length/2);
    
           return index > 0 ? input.Insert(index, "<br />") : input;
        }
    

    我将其作为单独的方法进行,但您应该能够轻松地将其更改为您的扩展方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2022-08-18
      • 2017-10-03
      • 2016-06-20
      • 1970-01-01
      相关资源
      最近更新 更多