经过几次没有结果的搜索后,我来征求你的帮助。我有一个小问题。我有两个字符串:
String values = "acceikoquy";
String values2 = "achips";
我会在这里得到相同数量的字符:
3
你知道怎么做吗?
我的代码:
String values = "acceikoquy";
String values2 = "achips";
int test = StringUtils.countMatches(values, values2);
System.out.println(test);
答案 0 :(得分:1)
这样的事情:
public static int sameCharsCount(String left, String right, boolean countDuplicates) {
if ((null == left) || (null == right))
return 0;
HashMap<Character, Integer> occurence = new HashMap<Character, Integer>();
for (int i = 0; i < left.length(); ++i) {
Character ch = left.charAt(i);
if (!occurence.containsKey(ch))
occurence.put(ch, 1);
else
occurence.put(ch, occurence.get(ch) + 1);
}
int result = 0;
for (int i = 0; i < right.length(); ++i) {
Character ch = right.charAt(i);
if (occurence.containsKey(ch)) {
result += 1;
if (!countDuplicates || occurence.get(ch) <= 1)
occurence.remove(ch);
else
occurence.put(ch, occurence.get(ch) - 1);
}
}
return result;
}
...
String values = "acceikoquy";
String values2 = "achips";
//TODO: put true or false if you want to count duplicates or not
int result = sameCharsCount(values, values2, true); // <- returns 3
int withDups = sameCharsCount("aaba", "caa", true); // <- 2 (two 'a' are shared)
int noDups = sameCharsCount("aaba", "caa", false); // <- 1 (just a fact, 'a' is shared)
答案 1 :(得分:0)
你可以这样试试
String values = "acxa";
String values2 = "abada";
int count=0;
List<Character> list=new ArrayList<>();
List<Character> list1=new ArrayList<>();
for(int i=0;i<values2.length();i++){
list.add(values2.charAt(i));
}
for(int i=0;i<values.length();i++){
list1.add(values.charAt(i));
}
ListIterator<Character> listIterator=list.listIterator();
while (listIterator.hasNext()){
char val=listIterator.next();
if(list1.toString().contains(""+val)){
count++;
listIterator.remove();
int index=list1.indexOf(val);
list1.remove(index);
}
}
System.out.println(count);
Out put:
2