Count the Number of matching characters in a pair of Java string


In order to find the count of matching characters in two Java strings the approach is to first create character arrays of both the strings which make comparison simple.After this put each unique character into a Hash map.

Compare each character of other string with created hash map whether it is present or not in case if present than put that character into other hash map this is to prevent duplicates.In last get the size of this new created target hash map which is equal to the count of number of matching characters in two given strings.

Example

 Live Demo

import java.util.HashMap;
public class MatchingCharacters {
   public static void main(String[] args) {
      String str1 = "abcccdef";
         String str2 = "dfgterf";
         char[] arr = str1.toCharArray();
         char[] arr2 = str2.toCharArray();
         HashMap<Character,Integer> hMap = new HashMap<>();
         HashMap<Character,Integer> hMap2 = new HashMap<>();
         for(int i = 0 ; i < arr.length ; i++) {
            if(!hMap.containsKey(arr[i])) {
            hMap.put(arr[i],1);
         }
      }
      for(int i = 0 ;i <arr2.length ;i++) {
         if(hMap.containsKey(arr2[i])) {
            hMap2.put(arr2[i],1);
         }
      }
      System.out.println("Number of matching characters in a pair of Java string is : " + hMap2.size());
   }
}

Output

Number of matching characters in a pair of Java string is : 3

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements