我使用数组查找两个字符串(即str2和str3 )之间的差异。当我使用下面的代码时,它完美地工作,并返回预期的输出。但当我取代
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);
}发布于 2013-10-30 11:31:16
要解决问题,请使用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()是返回boolean,而不是removeAll()的
发布于 2013-10-30 11:36:53
从我看到的地方:看起来您需要比较用逗号分隔的标记。创建strs的字符串列表(按',‘拆分),然后您可以删除类似的字符串,剩余的字符串可以比较不同。
https://stackoverflow.com/questions/19680572
复制相似问题