如何在字符串中计算特殊字符数量

3

你可以从这个链接中获取更多的想法:字符串中子串出现的次数 - Bigger
3个回答

8

使用replaceAll:

    String str = "one$two$three$four!five@six$";

    int count = str.length() - str.replaceAll("\\$","").length();

    System.out.println("Done:"+ count);

输出:

Done:4

使用 replace 而不是 replaceAll 会减少资源的消耗。我刚才用 replaceAll 来演示,因为它可以搜索 regex 模式,而这正是我最常用它的原因。

注意: 使用 replaceAll 时需要转义 $,但是使用 replace 则无需这样做:

str.replace("$");
str.replaceAll("\\$");

两种都正确,非常感谢你们两个。我使用第二种方法,它很容易。 - sivanesan1

3
你可以直接遍历字符串中的 字符
    String str = "one$two$three$four!five@six$";
    int counter = 0;
    for (Character c: str.toCharArray()) {
        if (c.equals('$')) {
            counter++;
        }
    }

2
String s1 = "one$two$three$four!five@six$";

String s2 = s1.replace("$", "");

int result = s1.length() - s2.length();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接