0

我正在使用 arraylists 来查找两个字符串之间的差异,str2str3. 当我使用下面的代码时,它可以完美运行并返回预期的输出。但是当我更换

str2 = #19, 6th cross, 7th main road, townname, cityname-560036
str3 = #19, 6th cross, 17th main road, townname, cityname-560036  

预期的输出应该是:al1 的内容:[1]

但我得到的输出是: al1 的内容:[]

谁能解释我哪里出错了?

提前致谢。

这是我的 doPost 方法:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
            str2="Hello";
    str3="Hallo";
    System.out.println("-------");
    System.out.println("This is first string:"+""+str2);
    System.out.println("This is second string:"+""+str3);


    ArrayList al = new ArrayList();
    ArrayList al1=new ArrayList(); 

      System.out.println("Initial size of al: " + al.size());

      // add elements to the array list
      for (int i = 0;i < str2.length(); i++)
        {
            al.add(str2.charAt(i));
        }
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);



      for (int i = 0;i < str3.length(); i++)
        {
            al1.add(str3.charAt(i));
        }

      System.out.println("Contents of al1: " + al1);

      System.out.println("Size of al1 after additions: " + al1.size());
        boolean hg=al1.removeAll(al);
        System.out.println("Remove All:"+hg);


      System.out.println("Contents of al: " + al);
      System.out.println("Contents of al1: " + al1);

}
4

3 回答 3

3

您已经在“#19”这里有了字符 '1',所以当您调用 remove all 时,所有的 '1' 都将被删除,包括您希望保留的那个。我认为您应该遍历字符并提取差异,否则比较不会很准确。

于 2013-10-30T11:16:10.933 回答
1

要解决您的问题,请使用该String .split()方法

str2 = #19, 6th cross, 7th main road, townname, cityname-560036
str3 = #19, 6th cross, 17th main road, townname, cityname-560036

String[] s2 = str2.split(",");
String[] s3 = str3.split(",");

for (int i = 0; i < s2.length; i++) {
    al.add(s2[i]);
}

for (int i = 0; i < s3.length; i++) {
    al1.add(s2[i]);
}

al.retainAll(al1);

System.out.println("Size of a1 is " + a1.size());

另外,我认为您想要retainAll()而不是removeAll(). retainAll()是返回 a 的那个boolean,而不是removeAll()

于 2013-10-30T11:31:16.203 回答
1

从我看到的地方:看起来您需要比较用逗号分隔的标记。创建strs的字符串列表(用','分割),然后你可以删除相似的字符串,剩下的可以比较差异。

于 2013-10-30T11:36:53.547 回答