1.正规表达式:System.Text.RegularExpressions.Regex.Replace(str, "([ ]+)", "") -- str是输入或要检测的字符串。
2.使用字符串自带的Replace方法:str.Replace(" ","")------------- str是输入或要检测的字符串。
3.由于空格的ASCII码值是32,因此,在去掉字符串中所有的空格时,只需循环访问字符串中的所有字符,并判断它们的ASCII码值是不是32
即可。去掉字符串中所有空格的关键代码如下:
CharEnumerator CEnumerator = textBox1.Text.GetEnumerator();
while (CEnumerator.MoveNext())
{
byte[] array = new byte[1];
array = System.Text.Encoding.ASCII.GetBytes(CEnumerator.Current.ToString());
int asciicode = (short)(array[0]);
if (asciicode != 32)
{
textBox2.Text += CEnumerator.Current.ToString();
}
}
这里的3种方法只能去除半角空格,不能去除全角空格。
str = str.Replace( " ", " ");
str = str.Replace( " ", "");
Label1.Text = str;
这样就可以把string中的所有空格去掉了.
4.
using System.Text.RegualrExpression;
Regex regex = new Regex( "\\s+ ");
string str = regex.Replace(textBox1.Text, " ");
这样不光会消除空格,所有的空白字符(回车换行、空格、制表符)都会被除去。
5.
using System;
using System.Collections.Generic;
using System.Text;
class TrimAll
{
string trimAllSpace(string str)
{
string temp = "";
for (int i = 0; i < str.Length; i++)
if (str[i] != ' ')
temp += str[i].ToString();
return temp;
}
public static void Main()
{
TrimAll ta = new TrimAll();
string testStr = "I Love China! I Love Chinese People!";
string reStr = ta.trimAllSpace(testStr);
Console.WriteLine("源字符串:" + testStr);
Console.WriteLine("去掉空格后的字符串:"+reStr);
}
}