前言,
想要检测一个文本框中,用逗号相隔的一些字符串是否有重复的出现,用到了一个小小的遍历。
代码演示:
private void button1_Click(object sender, EventArgs e) { string oldphone = textBox5.Text.TrimEnd(','); string exphone = oldphone + ","; //为了防止到最后一次循环length为0 string newphone = ""; if (oldphone.IndexOf(',') < 0) { textBox1.Text = oldphone; } else { for (int i = 0; i < oldphone.Split(',').Length; i++) { string a = exphone.Substring(0, exphone.IndexOf(',')); string b = exphone.Substring(a.Length + 1, exphone.Length - a.Length - 1); if (!b.Contains(a)) //检测是否有重复字段出现! { newphone += a + ","; } exphone = exphone.Substring(exphone.IndexOf(',') + 1, exphone.Length - exphone.IndexOf(',') - 1); textBox1.Text = newphone.TrimStart(',').TrimEnd(','); } } }
转载于:https://blog.51cto.com/kingboat/1376408