C#去除字符串空格的几种方法收藏

1.正规表达式:System.Text.RegularExpressions.Regex.Replace(str, "([ ]+)", "") --   str是输入或要检测的字符串。

2.使用字符串自带的Replace方法:str.Replace(" ","")-------------   str是输入或要检测的字符串。

3.由于空格的ASCII码值是32,因此,在去掉字符串中所有的空格时,只需循环访问字符串中的所有字符,并判断它们的ASCII码值是不是32即可。去掉字符串中所有空格的关键代码如下:

  1. CharEnumerator CEnumerator = textBox1.Text.GetEnumerator();
  2. while (CEnumerator.MoveNext())
  3. {
  4. byte[] array = new byte[1];
  5. array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
  6. int asciicode = (short)(array[0]);
  7. if (asciicode != 32)
  8. {
  9. textBox2.Text += CEnumerator.Current.ToString();
  10. }
  11. }

这里的3种方法只能去除半角空格,不能去除全角空格。

posted @ 2010-05-18 10:19  $walker  阅读(600)  评论(0)    收藏  举报