C#去除字符串空格

csharp

浏览数:1,598

2019-1-8

           //方法1,用字符处理
           
            string s = "     Mytest             quite               long    ";
            string[] word = s.Split(new char[] {' '});
            StringBuilder sb = new StringBuilder();
            foreach (string temp in word)
            {
                if (temp != " ")
                {
                    sb.Append(temp);
                }
               
            }
             Console.WriteLine(sb);

                  ///方法2,用ASCII
            ////由于空格的ASCII码值是32,因此,在去掉字符串中所有的空格时,
            ///只需循环访问字符串中的所有字符,并判断它们的ASCII码值是不是32即可。去掉字符串中所有空格
            string b = "     Mytest             quite               long    ";
            Console.WriteLine(b.Replace("             ", ""));
            Console.ReadKey();
            string a = "";
            string c = " ";
            CharEnumerator myenum = b.GetEnumerator();
            while (myenum.MoveNext())
            {
                byte[] array = new byte[1];
                array = System.Text.Encoding.ASCII.GetBytes(myenum.Current.ToString());
                int asciiCode = (short)(array[0]);
                if (asciiCode != 32)
                {
                    a += myenum.Current.ToString();
                }

            }
            Console.WriteLine(a);