如何计算字符串中的特殊字符
可能重复:
String函数如何计算字符串行中的分隔符
我有一个字符串as 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向你展示了它,因为它可以搜索正则表达式模式,这就是我最常用的模式。
注意:使用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();