Count the number of characters in the string (extension)

Count the number of characters in a string

1. Simple statistics times

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

Note: the first parameter represents the string to be counted, and the second parameter is the character to be counted.
The idea is to define an object to hold the results of the comparison.

2. The most frequent character

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

3. The first repeated character

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

4. Count the number of times the substring is in the parent string

The previous code was for a single character, which would not work if it was a string.

For string:
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 

Posted on Tue, 07 Jan 2020 04:07:47 -0800 by I Am Chris