检查字符串是否包含另一个字符串的所有字符

Tob*_*lor 0 java string string-comparison

String one = "This is a test";
String two = "This is a simple test";
Run Code Online (Sandbox Code Playgroud)

我想检查是否two包含所有字符one,并忽略它有额外字符的事实.

Mur*_*nik 9

最快的可能是将它们分解为HashSets然后应用containsAll

public static Set<Character> stringToCharacterSet(String s) {
    Set<Character> set = new HashSet<>();
    for (char c : s.toCharArray()) {
        set.add(c);
    }
    return set;
}

public static boolean containsAllChars
    (String container, String containee) {
    return stringToCharacterSet(container).containsAll
               (stringToCharacterSet(containee));
}

public static void main(String[] args) {
    String one = "This is a test";
    String two = "This is a simple test";
    System.out.println (containsAllChars(one, two));
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我们检查字符串“ABCD”和“ACC”,它将不起作用。它将返回“true”,因为 C 将被比较一次。 (2认同)