看範例學C#-24 剔除重複字串

  • 11363
  • 0
  • C#
  • 2011-10-07

看範例學C#-24 剔除重複字串

本例是使用 Regex.Split 來以textbox1的斷行符號來做分割

Regex.Split 方法 請參考MSDN

然後把每一行的字串塞到陣列str裡面去

而陣列有一個Distinct方法,可以剔除重除字串

所以接著只要用foreach 把剩下的值填回去textBox1去就完成了

foreach (string strlist in str.Distinct())

{

    textBox1.Text += strlist + "\r\n";

}

 

以下為本例完整程式碼

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace ex24
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string[] str = Regex.Split(textBox1.Text, "\r\n");
            textBox1.Text = "";
            foreach (string strlist in str.Distinct())
            {
                textBox1.Text += strlist + "\r\n";
            }
        }
    }
}

ex24.rar


如有錯誤 歡迎指正