Home > OS >  java - check If a String contains all characters of another String, but not in order
java - check If a String contains all characters of another String, but not in order

Time:01-19

I need a Method that takes all the characters of a String and checks if those characters are in another String.

The Method I have:

public boolean isItemUsable2(String word1, String word2) {
        int count = 0;
        for (int i = 0; i < word2.length(); i  ) {
            String itemPiece = Character.toString(word2.charAt(i));
            if (word1.contains(itemPiece)) {
                count  ;
            }
        }
        return count == word2.length();
    }

The problem is, for example word 1 is "12345 " and word 2 is "155" it should say it's false since there is only one 5, but it shows true and I don't know how to fix it.

CodePudding user response:

You can solve this problem by using a List of characters for the search word. Attempt to remove each test character from the list. If it is successfully removed, you know word1 contained the character while simultaneously preventing it from being checked again.

public static boolean isItemUsable2(String word1, String word2)
{
    final List<Character> word1Chars = new ArrayList<>();
    for (char aChar : word1.toCharArray())
        word1Chars.add(aChar);
    boolean usable = !word2.isEmpty();
    for (int i = 0; i < word2.length() && usable; i  )
    {
        usable = word1Chars.remove((Character) word2.charAt(i));
    }
    return usable;
}

CodePudding user response:

I would use regex. This isn't the most efficient way to do it, but it will work

public static boolean isItemUsable2(String a, String b) {
    Map<Character, Integer> map = new HashMap<>();
    for (char c : b.toCharArray()) {
        map.merge(c, 1, (k,v) -> v   1);
    }

    for (Entry<Character, Integer> entry : map.entrySet()) {
        Pattern pattern = Pattern.compile(Pattern.quote(entry.getKey().toString())   "{"   entry.getValue()   "}");
        if (!pattern.matcher(a).find()) {
            return false;
        }
    }
    return true;
}
  • Related