假设我有这个字符串:
String helloWorld = "One,Two,Three,Four!";
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能计算出逗号的数量String helloWorld?
cor*_*iKa 20
最简单的方法是遍历String并计算它们.
int commas = 0;
for(int i = 0; i < helloWorld.length(); i++) {
if(helloWorld.charAt(i) == ',') commas++;
}
System.out.println(helloWorld + " has " + commas + " commas!");
Run Code Online (Sandbox Code Playgroud)
int numberOfCommas = helloWorld .replaceAll("[^,]","").length();
Run Code Online (Sandbox Code Playgroud)
您可以在此站点中找到更多实现
| 归档时间: |
|
| 查看次数: |
16232 次 |
| 最近记录: |