WEB开发网
开发学院WEB开发ASP 输出到html页面的字符串的格式化 阅读

输出到html页面的字符串的格式化

 2007-01-21 10:36:07 来源:WEB开发网   
核心提示:当使用Response.Write()函数将字符串输出到html页面时候,因为html的默认实体的问题,输出到html页面的字符串的格式化,有时候输出并不是预期的那样,比如:Response.Write("hi tom"); //字符串中间有六个空格在web页面的显示却是: hi tom //h

当使用Response.Write()函数将字符串输出到html页面时候,因为html的默认实体的问题,有时候输出并不是预期的那样。比如:
Response.Write("hi    tom");  //字符串中间有六个空格
在web页面的显示却是: hi tom //html自动将连续的空格合并为一个

要达到预期的效果,必须象下面这样:
Response.Write("hi   tom");

这样显得很繁琐,你可以写一个函数来自动帮你将" "换成; 。代码如下:
------------------------------------------------------------------
public string FormatString(string str)
{
 str=str.Replace(" "," ");
 str=str.Replace("<","<");
 str=str.Replace(">",">");
 str=str.Replace('\n'.ToString(),"<br>");
 return str;
}
------------------------------------------------------------------

这样,要输出"hi    tom"的话,可以写成:
-------------------------------------
string str1 = "hi    tom" ;
Respone.Write(FormatString(str));
-------------------------------------
比如,下面的语句:
------------------------------------------------
string str1 = "Hi , Tom\nHi , Jim\n<===>";
Response.Write(FormatString(str1));
------------------------------------------------
在web页面上的输出为:
Hi , Tom
Hi , Jim
<===>

当然,你可以为这个函数扩充更多的功能。

Tags:输出 html 页面

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接