returnStrNum: function(str, who) {
var strNum = {};
for (var i = 0, l = str.length; i < l; i++) {
strNum[str[i]] = (strNum[str[i]] + 1) || 1;
}
return strNum[who];
},
console.log(that.returnStrNum('sgdgfdgrrgdv', 'g'));//4
说明:第一个参数表示被统计的字符串,第二个参数是需要统计的字符。 思想,定义一个对象保存比较的结果。
returnStrNum: function(str) {
var strNum = {};
var arr = [];
var keys = 1;
for (var i = 0, l = str.length; i < l; i++) {
strNum[str[i]] = (strNum[str[i]] + 1) || 1;
}
for (const key in strNum) {
if (strNum.hasOwnProperty(key)) {
const element = strNum[key];
if (element > keys) {
arr = key;
keys = element;
}
}
}
return arr + ':' + keys;
},
console.log(that.returnStrNum('sgdgfdgrrgdv'));//g:4
returnStrNum: function(str) {
var strNum = {};
for (var i = 0, l = str.length; i < l; i++) {
strNum[str[i]] = (strNum[str[i]] + 1) || 1;
if (strNum[str[i]] == 2) {
return str[i];
}
}
},
console.log(that.returnStrNum('sgdgfdgrrgdv'));//g
之前的代码针对的是单个字符,如果是字符串的话就行不通了。
returnStrNum: function(str, subStr) {
var sum = 0;
var begin = 0;
do {
begin = str.indexOf(subStr, begin);
if (begin != -1) {
sum++;
begin += subStr.length;
}
} while (begin != -1)
return sum;
},
console.log(that.returnStrNum('sgdgfdgrrgdv', 'dg'));//2