C#中Trim()使用小技巧 去除字符串中的特殊字符

经常使用Trim来清除字符串中的空格,其实也可以使用Trim来清除字符串中的特殊字符。

下面是一个小例子:

前台代码:

ContractedBlock.gif ExpandedBlockStart.gif View Code
 
   
1 < html xmlns = " http://www.w3.org/1999/xhtml " >
2   < head runat = " server " >
3 < title > Trimi小技巧 </ title >
4   </ head >
5   < body >
6 < form id = " form1 " runat = " server " >
7 < div >
8 < asp:TextBox ID = " txtTrim " runat = " server " ></ asp:TextBox >
9 < asp:Button ID = " btnTrim " runat = " server " Text = " 确定 " OnClick = " btnTrim_Click " />
10 </ div >
11 </ form >
12   </ body >
13   </ html >

在前台添加一个文本框和一个按钮,文本框用于输入字符串,单击“确定”按钮后,清除文本框字符串中的特殊字符。

后台代码:

ContractedBlock.gif ExpandedBlockStart.gif View Code
 
   
1 using System;
2   using System.Collections;
3   using System.Configuration;
4   using System.Data;
5   using System.Linq;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13
14 public partial class Trim : System.Web.UI.Page
15 {
16 protected void Page_Load( object sender, EventArgs e)
17 {
18
19 }
20 protected void btnTrim_Click( object sender, EventArgs e)
21 {
22 char [] TrimChar = { ' ' , ' - ' , ' \' ' , ' \" ' , ' \\ ' }; // 此处使用了转义字符如:\',\",\\,分别表示单引号,双引号,反斜杠
23 txtTrim.Text = this .txtTrim.Text.Trim(TrimChar);
24 }
25 }

使用 Trim只能清除字符型的特殊符号,其它字符串类型的特殊符号不能清除,例如:“insert”,“update”等,因为Trim只支持Char[]参数类型的重载,例如: Trim(char[] trimChars)

如果想更具体的了解Trim的用法,可以参考VSS文档中的String.Trim

 

转载于:https://www.cnblogs.com/shanaihuan/archive/2011/04/13/2014565.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>