现在的位置: 首页 > 综合 > 正文

asp.net中去除字符串中的所有空格字符

2013年05月18日 ⁄ 综合 ⁄ 共 747字 ⁄ 字号 评论关闭

方法一、最常用的就是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);

抱歉!评论已关闭.