0

After several searches that did not result, I have come to ask your help. I have a slight problem. I have two string:

String values = "acceikoquy";
String values2 = "achips";

I would get the same number of characters so here:

3

Do you have any idea how to do that?

My code :

String values = "acceikoquy";
String values2 = "achips";

int test = StringUtils.countMatches(values, values2);

System.out.println(test);
Julien
  • 53
  • 10

2 Answers2

1

Something like this:

  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)
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You can try in this way

 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
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
  • Counterexample: `values = "acxa"; and values2 = "abada";` returns `3` when `2` is expected (if duplicates are not count `1` is expected) – Dmitry Bychenko Oct 02 '14 at 10:39