可能是重复问题:
String Functions how to count delimiter in string line
我有一个字符串,如str = "one$two$three$four!five@six$",现在如何使用Java代码计算该字符串中"$"的总数。
可能是重复问题:
String Functions how to count delimiter in string line
我有一个字符串,如str = "one$two$three$four!five@six$",现在如何使用Java代码计算该字符串中"$"的总数。
使用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("\\$");
字符
: String str = "one$two$three$four!five@six$";
int counter = 0;
for (Character c: str.toCharArray()) {
if (c.equals('$')) {
counter++;
}
}
String s1 = "one$two$three$four!five@six$";
String s2 = s1.replace("$", "");
int result = s1.length() - s2.length();