方法一、最常用的就是Replace函数
string str = "str=1 3 45. 7 8 9 0 5";
Response.Write(str.Replace(" ",""));
方法二:由于空格的ASCII码值是32,因此,在去掉字符串中所有的空格时,只需循环访问字符串中的所有字符,并判断它们的ASCII码值是不是32即可。去掉字符串中所有空格的关键代码如下:
using System.Collections;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string s = "str=1 3 45. 7 8 9 0 5";
Response.Write(tripBlank(s));
}
}
public string tripBlank(string s)
{
string newstr = string.Empty;
CharEnumerator ce = s.GetEnumerator();
while (ce.MoveNext())
{
byte[] array = new byte[1];
array = System.Text.Encoding.ASCII.GetBytes(ce.Current.ToString());
int asciicode = (short)(array[0]);
if (asciicode != 32)
{
newstr+= ce.Current.ToString();
}
}
return newstr;
}
方法三:利用Split函数来实现
string s = "str=1 3 45. 7 8 9 0 5";
string ns = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Response.Write(ns);