位置:海鸟网 > IT > ASP.NET >

ASP.NET实现纯文本转HTML

ASP.NET实现纯文本转HTML ,可以实现的功能:输入:"ab\r\ncde\r\nfghi"输出:"<p>ab</p><p>cde</p><p>fghi</p>",注意无论任何输出<p>和</p>都要配对出现,且<p>和</p>之间不能为空

public static string Text2HtmlSimple(string input)

02 {

03     StringBuilder sb = new StringBuilder();

04     sb.Append("<p>");

05     int index = 0;

06     do

07     {

08         string toAppend = string.Empty;

09         int pos = input.IndexOf("\r\n", index);

10         if (pos == 0)

11         {

12             index = pos + 2;

13         }

14         else if (pos == input.Length - 2)

15         {

16             toAppend = input.Substring(index, pos - index);

17             if (!string.IsNullOrEmpty(toAppend))

18             {

19                 sb.AppendFormat("{0}</p>", toAppend);

20             }

21             index = pos + 2;

22         }

23         else if (pos > 0)

24         {

25             toAppend = input.Substring(index, pos - index);

26             if (!string.IsNullOrEmpty(toAppend))

27             {

28                 sb.AppendFormat("{0}</p><p>", toAppend);

29             }

30             index = pos + 2;

31         }

32         else

33         {

34             toAppend = input.Substring(index, input.Length - index);

35             sb.AppendFormat("{0}</p>", toAppend);

36             break;

37         }

38     }

39     while (index < input.Length);

40     return sb.ToString();

41 }