Skip to content
Advertisement

Comparing string array to a character array

String[] dictionaryArr= new String[]{"mee","go","bat","me","eat","goal","boy","run","go"};

char[] characterArr={'e','o','b','a','m','g','l'};

OR

String[] characterArr= new String[]{"e","o","b","a","m","g","l"};

I want to compare dictionaryArr to characterArr in such a way that it will

output: go, me, goal

Note: it did’nt output “mee” because letter “e” is repeated and there is only one ‘e’ in characterArr also it shouldn’t print “go” twice

Here’s what I have so far:

for (int i = 0; i < dictionaryArr.length ; i++) {
    for (int j = 0; j < characterArr.length ; j++) {
        if (dictionaryArr[i] == characterArr[j]) {
            System.out.println(dictionaryArr[i]);
        }
    }
}

Advertisement

Answer

You’re printing the word as soon as you find a matching letter. What you need to do is print it only after there are no missing letters. One way to do that is to create a list and check and remove each character as you iterate:

private static boolean matches(String word, String[] characterArr) {
    List<String> chars = new ArrayList<>(Arrays.asList(characterArr));
    for (String c : word.split("")) {
        if (!chars.remove(c)) {
            return false;
        }
    }
    return true;
}

We can call this in a distinct stream to easily avoid duplicate words:

Arrays.stream(dictionaryArr)
        .distinct()
        .filter(word -> matches(word, characterArr))
        .forEachOrdered(System.out::println);

Ideone Demo

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement