开发笔记1:C#如何将两个字符串去掉重复部分

       字符串str1="45500A123F00000125000X", 字符串str2="45500A123F00100025000X"。两个字符串代表的是一个条码范围,绿色部分代表的是条码的流水(1~1000)。在不清楚流水截取规则,可以通过下面算法自动去重,获取到条码流水。

 代码如下:

   #region 去掉两者相同的部分
        public static void RemoveLike(string str1, string str2, ref string str1Result, ref string str2Result)
        {


            //从左往右去重
            for (int index = 0; index < str1.Length; index++) //从左往右逐位截取
            {

                if (index == (str1.Length - 1)) //无重复的情况下,进行截取
                {
                    str1Result = str1.Substring(index, str1.Length - index);
                    str2Result = str2.Substring(index, str2.Length - index);
                    break;
                }
                else if (str1.Substring(index, 1) == str2.Substring(index, 1)) //重复自动跳过
                {
                    continue;
                }
                else //存在重复情况下,从左截取
                {
                    str1Result = str1.Substring(index, str1.Length - index);
                    str2Result = str2.Substring(index, str2.Length - index);
                    break;
                }
            }
            //再从右往左去重
            for (int index = str1Result.Length - 1; index > 0; index--)
            {

                if (index == 0) //无重复的情况下,进行截取
                {
                    str1Result = str1Result.Substring(0, 1);
                    str2Result = str2Result.Substring(0, 1);
                    break;
                }
                else if (str1Result.Substring(index, 1) == str2Result.Substring(index, 1))//重复自动跳过
                {
                    continue;
                }
                else//存在重复情况下,从左截取
                {
                    str1Result = str1Result.Substring(0, index + 1);
                    str2Result = str2Result.Substring(0, index + 1);
                    break;
                }
            }

        }
        #endregion

调用:

            string str1 = "45500A123F00000125000X";
            string str2 = "45500A123F00100025000X";
            string result1 = "";
            string result2 = "";
            RemoveLike(str1, str2, ref result1, ref result2);

结果:

原字符串1:45500A123F00000125000X
原字符串2:45500A123F00100025000X
去重后字符串1=0001
去重后字符串2=1000