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

标签 java string string-comparison

String one = "This is a test";
String two = "This is a simple test";

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

最佳答案

最快的方法可能是将它们分解为 HashSet,然后应用 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));
}

关于java - 检查一个字符串是否包含另一个字符串的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27668213/

相关文章:

C# 字符串比较等于 false

.net - StringComparison.Ordinal 是否与 InvariantCulture 相同,用于测试相等性?

java - 尝试结束 session 时应用程序崩溃..空对象引用

java - 如何将overlayItem 对象添加到数组中?

java - 使用 ThreadPool 和 JMS 时处理 JVM 崩溃

javascript - 在 JavaScript 中替换之后

cocoa-touch - 比较两个 NSStrings

java - 读取/写入 jar 文件内的属性文件

c# - 删除字符串中最后一次出现定界符之后的字符

string - Haskell 将字符串转换为整数列表