English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
To find the number of matching characters in two Java strings, the method is to first create character arrays of the two strings to make comparison easier, and then put each unique character into the hash map.
Compare each character of other strings with the created hash map to prevent adding the character to other hash maps in case (if it exists) to prevent repetition. Finally, get the size of the newly created target hash map, which is equal to the count of matching characters in the two given strings.
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("The number of matching characters in a pair of Java strings is : "); + hMap2.size()); } }
The number of matching characters in a pair of Java strings is : 3