开发笔记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
 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值