onlytiancai

谁能写一个函数,实现如下功能,不需要调试一次就通过,且没有BUG。需求:输入:"ab\r\ncde\r\nfghi"输出:"<p>ab</p><p>cde</p><p>fghi</p>",注意无论任何输出<p>和</p>都要配对出现,且<p>和</p>之间不能为空

public static string Text2HtmlSimple(string input)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<p>");
    int index = 0;
    do
    {
        string toAppend = string.Empty;
        int pos = input.IndexOf("\r\n", index);
        if (pos == 0)
        {
            index = pos + 2;
        }
        else if (pos == input.Length - 2)
        {
            toAppend = input.Substring(index, pos - index);
            if (!string.IsNullOrEmpty(toAppend))
            {
                sb.AppendFormat("{0}</p>", toAppend);
            }
            index = pos + 2;
        }
        else if (pos > 0)
        {
            toAppend = input.Substring(index, pos - index);
            if (!string.IsNullOrEmpty(toAppend))
            {
                sb.AppendFormat("{0}</p><p>", toAppend);
            }
            index = pos + 2;
        }
        else
        {
            toAppend = input.Substring(index, input.Length - index);
            sb.AppendFormat("{0}</p>", toAppend);
            break;
        }
    }
    while (index < input.Length);
    return sb.ToString();
}

分类:

技术点:

相关文章:

  • 2021-11-07
  • 2022-01-06
  • 2022-12-23
  • 2021-12-15
  • 2021-12-20
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-03
  • 2022-03-03
  • 2022-03-04
  • 2021-06-27
  • 2021-12-20
  • 2021-12-12
相关资源
相似解决方案