代码练习:简单的纯文本转HTML

谁能写一个函数,实现如下功能,不需要调试一次就通过,且没有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();
}

posted @ 2010-10-10 17:31  蛙蛙王子  Views(1287)  Comments(3Edit  收藏  举报