JS counts the number of occurrences of each character in a string

JS string deduplication method

Traverse new strings to remove duplicates

var str = 'abcabcabcdef'
var newStr = ''
for (var i = 0; i < str.length; i++) {
   if (!newStr.includes(str[i])) {
          newStr += str[i]
        }
    }
console.log(newStr)
Use objects to remove duplicates

        var str = 'abcabcabcdef'
        var obj = {}
        for(var i = 0;i<str.length;i++){
           obj[str[i]] = str[i]
        }
        console.log(obj)
        var newStr = ''
        for(var k in obj){
            newStr += obj[k]
        }
        console.log(newStr)

...........................

Count the number of occurrences of each character in each string

Dual loop counter

By default, there is already a deduplicated string. Use a loop to determine how many times each character of the string appears in the original string and record it with a counter.


     var str = 'abcabcabcdee'
        var newStr = 'abcde'
        for (var a = 0; a < newStr.length; a++) {
            str[a]
            var k = 0 // 定义计数器,用于统计当前str[a]的次数
            for (var b = 0; b < str.length; b++) {
                if (newStr[a] === str[b]) {
                    k++
                }
            }
            console.log(newStr[a] + '出现了' + k + '次');
        }
Use indexof() to search

If you use indexOf to find it, it is the subscript. If you cannot find it, it is -1. The second parameter represents where to start searching.


var str = 'abcabcabcdee'
        var newStr = 'abcde'
        for(var a = 0; a < newStr.length; a++) {
            var index = 0
            var k = 0
            while(index != -1) { //直到遍历查找的时候找不到停止
                index = str.indexOf(newStr[a], index)  //在str中查找newStr中的字符
                if(index != -1) {
                    k++     //统计出现次数
                    index++  //自增索引
                }
            }
       console.log(newStr[0] + '出现了' + k + '次');
        }
     

Use objects for deduplication and statistics


        var str = 'abcabcabcdef'
        var obj = {}
        for (var i = 0;i<str.length;i++){
            if(obj[str[i]]=== undefined){
                obj[str[i]] =1 //如果在对象中找不到则进行添加赋值
            }else{
                obj [str[i]] ++//找到就计数加1
            }
        }
        console.log(obj)

Guess you like

Origin blog.csdn.net/a_strong_pig/article/details/129707684