Comparing characters in 2 char Array using Java



I am a beginner in Java and I will like to know if there’s a way to compare characters in a char Array with other characters in another char Array in order to see if they have characters that match. Not to see if they contain exactly the same characters in the same sequence as most examples explain.

For instance:

char [] word1= {'a','c','f','b','e'};

char[] word2= {'a','b','c','d','e','h','j','f','i','m'};

and using maybe if statements to say that word1 contains the characters in word2 so it is correct. Else it is incorrect if word2 is missing at least one character that word1 has.

Answer

Try this. It will report if either array contains all the characters of the other. I used strings and converted them to arrays to facilitate the coding.

String[][] testData =
                { {"axyzx","xxyzaa"},
                  {"aaxyz","aaax"},
                  {"axa","a"},
                  {"arrs","asrrrs"},
                  {"acfbe","abcdehjfim"}};

for (String[] words : testData) {
    boolean result = contains(words[0].toCharArray(), words[1].toCharArray());
    String output = String.format("%s contains all %s","'"+words[0]+"'","'"+words[1]+"'");
    System.out.printf("%34s - %b%n", output, result);
    output = String.format("%s contains all %s","'"+words[1]+"'","'"+words[0]+"'");
    result = contains(words[1].toCharArray(), words[0].toCharArray());
    System.out.printf("%34s - %b%n%n", output, result);
}

Prints

     'axyzx' contains all 'xxyzaa' - false
     'xxyzaa' contains all 'axyzx' - true

       'aaxyz' contains all 'aaax' - false
       'aaax' contains all 'aaxyz' - false

            'axa' contains all 'a' - true
            'a' contains all 'axa' - false

      'arrs' contains all 'asrrrs' - false
      'asrrrs' contains all 'arrs' - true

 'acfbe' contains all 'abcdehjfim' - false
 'abcdehjfim' contains all 'acfbe' - true



  • Using a map, do a frequency count of the characters in the second array.
  • Now iterate thru the map using the first array, decrementing the character count when the character is found. When the count reaches 0, assign null to the value.
  • if map is now “empty”, the first array contains all characters of second array.
// see if first array contains all of second array,
// regardless of order of the characters
public static boolean contains(char[] ch1, char[] ch2) {
//  a smaller array cannot possible contain the same
//  characters as a larger array
    if (ch1.length < ch2.length) {
        return false;
    }
    Map<Character,Integer> map = new HashMap<>();
    // Do a frequency count
    for(char c : ch2) { 
        map.compute(c, (k,v)->v == null ? 1 : v+1);
    }
    // now decrement count for each occurrence
    // of character in first array, setting value to
    // null when count reaches 0.
    for(char c : ch1) {
        map.computeIfPresent(c, (k,v)-> v <= 1 ? null : v-1);
    }
    return map.isEmpty();
}


Source: stackoverflow