繁体   English   中英

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

[英]Comparing string character by character in Java

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

String value = "abaabb";

现在我怎么知道abaabb中只包含ab而没有其他字符,如cd 、...

为此,我想要一种比较abaabb单个字符的abaabb

您可以使用.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");    
    }
}

您可以将String#matches正则表达式一起使用

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

最简单的解决方案:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM