在Java中逐字符串地比较字符串

时间:2015-11-28 12:33:11

标签: java

如何比较存储在Java变量中的个别字符?

String value = "abaabb";

现在,我怎么知道abaabb只包含ab,而且cd等其他字符都不包含......

为此我想要一种方法来比较abaabb中的个别角色。

3 个答案:

答案 0 :(得分:1)

您可以使用.charAt()方法:

String x="aabbbb";
for (int i = 0; i < x.length(); i++) {
    if(x.charAt(i)=='a' || x.charAt(i)=='b') {
        System.out.println("a or b");    
    }
}

答案 1 :(得分:0)

您可以String#matches使用Regular Expression

boolean valid = "abaabb".matches("[ab]+");

答案 2 :(得分:-1)

最简单的解决方案:

    String value = "abaabb";
    Set<Character> letters = new HashSet<Character>();
    for(int i = 0; i < value.length(); i++){
        letters.add(value.charAt(i));
    }

//编辑 @Trincot 在集合中我们收集字符串中的唯一字符,然后我们可以用字母构建第二个集合来检查是否只有&#39; a&#39;和&#39; b&#39;在场

    Set<Character> check = new HashSet<>();
    check.add('a');
    check.add('b');
    letters.removeAll(check);
    System.out.println(letters.isEmpty());