如何计算字符串中的特殊字符

时间:2012-07-20 06:28:04

标签: java android

  

可能重复:
  String Functions how to count delimiter in string line

  

我有一个字符串为str =“one $ two $ three $ four!five @ six $”现在如何使用java代码计算该字符串中“$”的总数。

3 个答案:

答案 0 :(得分:6)

使用replaceAll:

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

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

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

打印:

Done:4

使用替换代替 replaceAll 将减少资源消耗。我只是通过 replaceAll 向您展示了它,因为它可以搜索正则表达式模式,这就是我最常用的模式。

注意:使用 replaceAll 我需要转义 $ ,但替换则不需要:

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

答案 1 :(得分:2)

您可以遍历字符串中的Characters

    String str = "one$two$three$four!five@six$";
    int counter = 0;
    for (Character c: str.toCharArray()) {
        if (c.equals('$')) {
            counter++;
        }
    }

答案 2 :(得分:2)

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

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

int result = s1.length() - s2.length();
相关问题