1. 程式人生 > >asp.net中去除字串中的所有空格字元

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

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