计算字符串中每个字符出现的次数

31

我希望使用JavaScript计算给定字符串中每个字符出现的次数。

例如:

var str = "I want to count the number of occurrences of each char in this string";

输出结果应为:

h = 4;
e = 4; // and so on 

我尝试在 Google 上搜索,但没有找到答案。我想要实现类似这个的功能;顺序不重要。

25个回答

2

您可以使用对象来完成任务。

步骤1 - 创建一个对象

步骤2 - 遍历字符串

步骤3 - 将字符作为键,字符计数作为值添加到对象中

var obj={}

function countWord(arr)
{
for(let i=0;i<arr.length;i++)
{
if(obj[arr[i]]) //check if character is present in the obj as key
{
    obj[arr[i]]=obj[arr[i]]+1; //if yes then update its value
}
else
{
    obj[arr[i]]=1; //initialise it with a value 1

}
}
}


1
希望这能帮助到某些人。
function getNoOfOccurences(str){
    var temp = {};
    for(var oindex=0;oindex<str.length;oindex++){
        if(typeof temp[str.charAt(oindex)] == 'undefined'){
            temp[str.charAt(oindex)] = 1;
        }else{
            temp[str.charAt(oindex)] = temp[str.charAt(oindex)]+1;
        }
    }
    return temp;
}

1

我尝试使用“空格”和“特殊字符”进行检查:

function charCount(str){
    const requiredString = str.toLowerCase();

    const leng = str.length;

    let output = {};

    for(let i=0; i<leng; i++){
        const activeCharacter = requiredString[i];
        if(/[a-z0-9]/.test(activeCharacter)){
            output.hasOwnProperty(activeCharacter) ? output[activeCharacter]++ : output[activeCharacter] = 1;
        }
    }
    return output;
}

1
let newStr= "asafasdhfasjkhfweoiuriujasfaksldjhalsjkhfjlkqaofadsfasasdfas";
       
function checkStringOccurnace(newStr){
    let finalStr = {};
    let checkArr = [];
    let counterArr = [];
    for(let i = 0; i < newStr.length; i++){
        if(checkArr.indexOf(newStr[i]) == -1){
            checkArr.push(newStr[i])
            let counter = 0;
            counterArr.push(counter + 1)
            finalStr[newStr[i]] = 1;
        }else if(checkArr.indexOf(newStr[i]) > -1){
            let index = checkArr.indexOf(newStr[i])
            counterArr[index] = counterArr[index] + 1;
            finalStr[checkArr[index]] = counterArr[index];
        }
    }
    return finalStr;
}

let demo = checkStringOccurnace(newStr);
console.log(" finalStr >> ", demo);

虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - Cookie
这是对一个老问题的很好的回答。我建议您修复格式并添加一些注释。此外,如果您要提供一个函数,最好返回一些内容,并将控制台日志作为示例放在函数外部。 - Blizzardengle

1
    package com.company;

import java.util.HashMap;


 public class Main {

    public static void main(String[] args) {
    // write your code here
    HashMap<Character, Integer> sHashMap = new HashMap();  // using hashMap<key , value > here key = character and  value = count

    String arr = "HelloWorld";

    for (int i = 0; i < arr.length(); i++) {
        boolean flag = sHashMap.containsKey(arr.charAt(i));  // check if char is already  present 

    if (flag == true)
        {
            int Count = sHashMap.get(arr.charAt(i)); // get the char count
            sHashMap.put(arr.charAt(i), ++Count); //   increment the count and update in hashMap
        } 
        else 
        {
            sHashMap.put(arr.charAt(i), 1); //if  char not present then insert into hashMap
        }
    }

     System.out.println(sHashMap);
    //OutPut would be like ths {r=1, d=1, e=1, W=1, H=1, l=3, o=2}

}

}

嗨!这是一个仅包含代码的答案,对其他人来说几乎没有任何价值。我可以请求您在代码周围包含一些解释吗?谢谢! - 10 Rep

1

 // Converts String To Array
        var SampleString= Array.from("saleem");

        // return Distinct count as a object
        var allcount = _.countBy(SampleString, function (num) {
            return num;
        });

        // Iterating over object and printing key and value
        _.map(allcount, function(cnt,key){
            console.log(key +":"+cnt);
        });

        // Printing Object
        console.log(allcount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

    <p>Set the variable to different value and then try...</p>
    


1
    function cauta() {

        var str = document.form.stringul.value;
        str = str.toLowerCase();
        var tablou = [];

        k = 0;
        //cautarea caracterelor unice
        for (var i = 0, n = 0; i < str.length; i++) {
            for (var j = 0; j < tablou.length; j++) {
                if (tablou[j] == str[i]) k = 1;
            }
            if (k != 1) {
                if (str[i] != ' ')
                    tablou[n] = str[i]; n++;
            }
            k = 0;
        }
        //numararea aparitilor
        count = 0;
        for (var i = 0; i < tablou.length; i++) {
            if(tablou[i]!=null){
            char = tablou[i];
            pos = str.indexOf(char);
            while (pos > -1) {
                ++count;
                pos = str.indexOf(char, ++pos);

            }

            document.getElementById("rezultat").innerHTML += tablou[i] + ":" + count + '\n';
            count = 0;
        }
        }

    }

这个函数会将每个唯一的字符放入数组中,然后找到每个字符在字符串中出现的次数。在我的情况下,我获取并将数据放入。

0
               let str = "aabbcc"
                 let obj = {}
               for (let item of str) {
                if (!obj[item]) {
                 obj[item] = 1
                } else {
               obj[item] = obj[item] + 1
                       }
                      }
               console.log(obj)

格式使得这很难理解。强烈建议解释一下你的解决方案,以及它与其他可能未被考虑的答案的不同之处。 - Kieran101

0

试一下

let txt = 'hello';
let txtArr = txt.split('');
let objCnt = txtArr.reduce((accum, currVal) => {
    accum[currVal] = (accum[currVal] || 0) + 1;
    return accum;
}, {});
console.log(objCnt);

0

我认为最少的代码行是最好的解决方案。就像这样。

let text= 'I want to count the number of occurrences of each char in this string';

const obj = {};

for (let i = 0; i < text.length; i++) {
    const ele = text[i];
    obj[ele] === undefined ? obj[ele] = 1 : obj[ele]++
}

console.log(obj);

第二个例子。

text.split('').forEach((ele) => {
    obj[ele] === undefined ? obj[ele] =1 : obj[ele]++ 
})
console.log(obj);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接