首页 > 代码库 > differ比较两个字符串的差异

differ比较两个字符串的差异

"abcde","abdefk"  ---->-c,+f,+k

"aba","aababb"    ----->+a,+b,+b

 

 1 import java.util.ArrayList; 2  3 public class differ { 4  5     public static void main(String[] args) { 6         System.out.println(differ("abcde","abdefk")); 7         System.out.println(differ("aba","aababb")); 8     } 9     public static String differ(String a,String b)10     {11         String plus="";12         String neg="";13         ArrayList arr=new ArrayList();14         for(int i=0;i<a.length();i++)15         {16             arr.add(a.charAt(i));17         }18         for(int j=0;j<b.length();j++)19         {20             if(arr.indexOf(b.charAt(j))!=-1)21                 arr.remove(arr.indexOf(b.charAt(j)));//说明有22             else23                 plus+=",+"+b.charAt(j);24         }25         for(int i=0;i<arr.size();i++)26             neg+="-"+arr.get(i);27         if(neg=="")28             plus=plus.substring(1);//去掉逗号29         return neg+plus;30     }31     32 }

结果:

differ比较两个字符串的差异