去掉字符串中的所有空格

实现效果:

关键知识:

(使用字符串的ToCharArray方法将字符串复制到Unicode字符数组,然后对其进行操作)

实现代码:

 1         private void button1_Click(object sender, EventArgs e)
 2         {
 3             if (textBox1.Text != string.Empty)
 4             {
 5                 if (button1.Text.Equals("清除")){
 6                   textBox1.Text = ""; textBox2.Text = "";
 7                     button1.Text = "去掉空格"; 
 8                 }else if(textBox1.Text!=string.Empty){
 9                                 char[] cha = textBox1.Text.ToCharArray();//得到字符数组
10                 IEnumerator ienumer = cha.GetEnumerator();//得到枚举器
11                 StringBuilder stringbuilder = new StringBuilder();
12                 while(ienumer.MoveNext()){  //开始枚举
13                     stringbuilder.Append(
14                         (char)ienumer.Current != ' ' ? //注意字符串内为空格 非空字符
15                         ienumer.Current.ToString():string.Empty);
16                 }
17                 textBox2.Text = stringbuilder.ToString();//得到没有空格的字符串
18                 button1.Text = "清除";
19                 }
20             }
21             else { MessageBox.Show("还没有输入嗷","提示:"); }
22         }
原文地址:https://www.cnblogs.com/feiyucha/p/9901224.html