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

时间:2014-12-27 14:33:58

标签: java string string-comparison

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

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

5 个答案:

答案 0 :(得分:9)

最快的可能是将它们分解为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));
}

答案 1 :(得分:1)

对第一个字符串中的字符集使用简单的循环:

String s1 = "This is a test";
String s2 = "This is a simple test";
Set<Character> chars = new HashSet<Character>();
for(int i = 0; i < s1.length(); i++) {
    chars.add(s1.charAt(i));
}


for (Iterator<Character> iterator = chars.iterator(); iterator.hasNext();) {
    Character character = iterator.next();
    if(!s2.contains(character.toString())) {
        // break and mark as not contained
        break;
    }
}

如果要检查单词,那么您可以将空格周围的字符串拆分为单词列表:

String[] words1 = s1.split("\\s");
String[] words2 = s2.split("\\s");

List<String> wordList1 = Arrays.asList(words1);
List<String> wordList2 = Arrays.asList(words2);
System.out.println(wordList2.containsAll(wordList1));

答案 2 :(得分:1)

static boolean stringContains(String longer, String shorter) {
    int i = 0;
    for (char c : shorter.toCharArray()) {
        i = longer.indexOf(c, i) + 1;
        if (i <= 0) { return false; }
    }
    return true;
}

答案 3 :(得分:0)

试试这个。我知道它很长但是有效

public static void main(String[] args) 
{
    String String1,String2;
    int i, j, count1, count2;
    count1 = 0;
    count2 = 0;
    String1 = "This is a test";
    String2 = "This is a simple test";
    char[] list1 = new char[String2.length()];
    char[] list2 = new char[String2.length()];
    char[] list3 = new char[String2.length()];
    for (i = 0; i <= String1.length() - 1; i++)
    {
        list1[i] = String1.charAt(i);
        for (j = 0; j <= String2.length() - 1; j++)
        {
            list2[j] = String2.charAt(j);
            if (list1[i] == list2[j])
            {
                i++;
                count1++;
            }
        }
    }
    for (i = 0; i <= String1.length() - 1; i++)
    {
        list1[i] = String1.charAt(i);
        for (j = 0; j <= String1.length() - 1; j++)
        {
            list3[j] = String1.charAt(j);
            if (list1[i] == list3[j])
            {
                i++;
                count2++;
            }
        }
    }

    if (count1 >= count2)
        System.out.println(true);
    else
        System.out.println(false);
}

答案 4 :(得分:0)

two.startsWith(one) 

如果您不确定起始位置(以上假设为0),请尝试使用以下API

startsWith(String, offset)