【发布时间】:2012-04-11 19:32:05
【问题描述】:
我有以下函数来计算字符串中逗号(或任何其他字符)的数量,而不计算双引号内的逗号。我想知道是否有更好的方法来实现这一点,或者即使你能找到这个函数可能崩溃的情况。
public int countCharOfString(char c, String s) {
int numberOfC = 0;
boolean doubleQuotesFound = false;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == c && !doubleQuotesFound){
numberOfC++;
}else if(s.charAt(i) == c && doubleQuotesFound){
continue;
}else if(s.charAt(i) == '\"'){
doubleQuotesFound = !doubleQuotesFound;
}
}
return numberOfC;
}
感谢您的建议
【问题讨论】:
-
用 switch 语句替换你的 if / else 东西。
标签: java string performance counter