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

siv*_*an1 3 java android

可能重复:
字符串函数如何计算字符串行中的分隔符

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

マルち*_* だよ 6

使用replaceAll:

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

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

    System.out.println("Done:"+ count);
Run Code Online (Sandbox Code Playgroud)

打印:

Done:4
Run Code Online (Sandbox Code Playgroud)

使用replace而不是replaceAll将减少资源密集度.我只是用replaceAll向你展示了它,因为它可以搜索正则表达式模式,这就是我最常用的模式.

注意:使用replaceAll我需要转义$,但使用replace时没有这样的需要:

str.replace("$");
str.replaceAll("\\$");
Run Code Online (Sandbox Code Playgroud)