Java - 计算字符串中的符号数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5098429/
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
Java - Count number of symbols in string
提问by test
Let's say I have this string:
假设我有这个字符串:
String helloWorld = "One,Two,Three,Four!";
How can I make it so it counts the number of commas in String helloWorld
?
我怎样才能让它计算逗号的数量String helloWorld
?
回答by corsiKa
the simplest way would be iterate through the String and count them.
最简单的方法是遍历字符串并计算它们。
int commas = 0;
for(int i = 0; i < helloWorld.length(); i++) {
if(helloWorld.charAt(i) == ',') commas++;
}
System.out.println(helloWorld + " has " + commas + " commas!");
回答by lukastymo
回答by Péter T?r?k
String[] tokens = helloWorld.split(",");
System.out.println("Number of commas: " + (tokens.length - 1));
回答by m0s
Not so simple but shorter way
不是那么简单而是更短的方式
String str = "One,Two,Three,Four!";
int num = str.replaceAll("[^,]","").length();
回答by Mahfuz Ahmed
If you can import com.lakota.utils.StringUtils then it's so simple. Import this> import com.lakota.utils.StringUtils;
如果您可以导入 com.lakota.utils.StringUtils 那就太简单了。导入这个>导入com.lakota.utils.StringUtils;
int count = StringUtils.countMatches("One,Two,Three,Four!", ",");
System.out.println("total comma "+ count);