本文共 2346 字,大约阅读时间需要 7 分钟。
现在项目中有需求比较两个字符串数组,找出其中不同的部分,并保存到本地txt。实现方式每个人都有自己的思路,这里提供一种通过归并排序实现的方式供大家参考。
基本思路是数组A和数组B对比,使用数组a来保存数组A中比数组B中多的元素(即在A中存在,B中不存在的元素),b来保存数据B中比数组A中多的元素(即B中存在,A中不存在的元素)。开始需要分别调用Sort()函数对A、B数组进行排序,然后使用CompareTo从两个数组中第一个数组进行比较,当A.0(A中第一个元素)>B.0时A.CompareTo(B)==1,当A.0=B.0时A.CompareTo(B)==0,当A.0<B.0时A.CompareTo(B)==-1。通过判断A.CompareTo(B)的值来执行a.add和b.add操作,最终就能得到a、b数组,然后写入到txt就可以了。
核心代码如下:
///调用:/// 归并排序: 查找两个集合中的不同数据 /// /// 源数据集合 /// 新数据集合 /// 需在源数据中移除的集合 /// 需在源数据中添加的集合 public void FindDistinct(Listroot, List source, out List remove, out List add) { remove = new List (); add = new List (); root.Sort(); source.Sort(); //foreach (string str in root) Console.WriteLine(str); //Console.WriteLine("\r\n"); //foreach (string str in source) Console.WriteLine(str); //Console.WriteLine("\r\n"); int i = 0, j = 0; while (i < root.Count && j < source.Count) { switch (root[i].CompareTo(source[j])) { case -1: remove.Add(root[i]); i++; break; case 0: i++; j++; break; case 1: add.Add(source[j]); j++; break; } } if (i < root.Count) { for (int m = i; m < root.Count; m++) remove.Add(root[m]); } else if (j < source.Count) { for (int m = j; m < source.Count; m++) add.Add(source[m]); } //Console.WriteLine("\r\nroot中不同的数据:"); //foreach (string str in remove) Console.WriteLine(str); //Console.WriteLine("\r\nsource中不同的数据:"); //foreach (string str in add) Console.WriteLine(str); }
List这里是对归并排序算法的一个小应用,希望对大家有所帮助,不足之处请大家批评指正。remove; List add; FindDistinct(rpqlist, pdflist, out remove, out add); //将strArray输出到文本文件 using (TextWriter tw = new StreamWriter(@"D:\RPQ.txt")) { int index = 0; foreach (string str in remove) { string s = string.Format("{0:d3}\t{1}", index, str); tw.WriteLine(s); index++; } } using (TextWriter tw = new StreamWriter(@"D:\PDF.txt")) { int index = 0; foreach (string str in add) { string s = string.Format("{0:d3}\t{1}", index, str); tw.WriteLine(s); index++; } } MessageBox.Show("数据对比完毕,文件已经保存到D盘!");
转载地址:http://spkum.baihongyu.com/