java 如何计算字符串中的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11573939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to count special character in a string
提问by sivanesan1
Possible Duplicate:
String Functions how to count delimiter in string line
可能的重复:
字符串函数如何计算字符串行中的分隔符
I have a string as str = "one$two$three$four!five@six$" now how to count Total number of "$" in that string using java code.
我有一个字符串 str = "one$two$three$four!five@six$" 现在如何使用java代码计算该字符串中“$”的总数。
回答by マルちゃん だよ
Using replaceAll:
使用 replaceAll:
String str = "one$two$three$four!five@six$";
int count = str.length() - str.replaceAll("\$","").length();
System.out.println("Done:"+ count);
Prints:
印刷:
Done:4
Using replaceinstead of replaceAllwould be less resource intensive. I just showed it to you with replaceAllbecause it can search for regexpatterns, and that's what I use it for the most.
使用replace而不是replaceAll会减少资源密集度。我刚刚用replaceAll向您展示了它,因为它可以搜索正则表达式模式,这就是我最常使用它的地方。
Note: using replaceAllI need to escape $, but with replacethere is no such need:
注意:使用replaceAll我需要转义$,但使用replace则不需要:
str.replace("$");
str.replaceAll("\$");
回答by Keppil
You can just iterate over the Characters
in the string:
您可以遍历Characters
字符串中的 :
String str = "one$two$three$four!five@six$";
int counter = 0;
for (Character c: str.toCharArray()) {
if (c.equals('$')) {
counter++;
}
}
回答by AncerHaides
String s1 = "one$two$three$four!five@six$";
String s2 = s1.replace("$", "");
int result = s1.length() - s2.length();