[VB6][VBA][VB.Net][C#.Net] 消除字串中的空格

  • 31655
  • 0
  • C#
  • 2008-11-30

[VB6][VB.Net][C#.Net] 消除字串中的空格

可以利用Replace將字串中的空格消除

VB6 / VBA

Private Sub Command1_Click()
    Me.Text2.Text = Replace(Me.Text1.Text, " ", "")
End Sub

 

1 1

C# .Net 2005
兩種方法:
一種是網路上找到的,認為還不錯
http://zhidao.baidu.com/question/64072325.html
另一種則是使用Replace,跟VB6的用法一樣

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            string YuanStr = "1 2 3 4 5      6";//源字符串
            textBox1.Text = YuanStr;
            string NewStr = "";//新字符串
            
            CharEnumerator CE = YuanStr.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();
                }
            }
            textBox2.Text = NewStr;
            //MessageBox.Show(NewStr);
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string str = "1a 3a 5a      7a";//源字符串
            textBox1.Text = str;
            textBox2.Text = str.Replace(" ", "");
            //MessageBox.Show(str);
        }
    }
}

  

1 1

 

VB.Net 2005
跟VB6的用法一樣

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox2.Text = Replace(TextBox1.Text, " ", "")
    End Sub
End Class

1

範例下載:消除字串中的空格.rar

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo