Count the number of occurrences of each character in a string

Counting the number of occurrences of each character in a string can be achieved using a hash table (also known as a dictionary or map). Specific steps are as follows:

  1. Iterate through the string, and for each character, use it as the key of the hash table and the number of times it occurs as the value of the hash table.
  2. If the character already exists in the hash table, add 1 to its corresponding value; otherwise, add the key in the hash table and set its value to 1.
  3. After the traversal is complete, the key-value pairs in the hash table represent the number of occurrences of each character in the string.

Here's a possible JavaScript implementation:

function countCharacters(str) {
    
    
  const count = {
    
    };
  for (const char of str) {
    
    
    count[char] = (count[char] || 0) + 1;
  }
  return count;
}

// 示例用法
const str = 'hello, world!';
const result = countCharacters(str);
console.log(result); // { h: 1, e: 1, l: 3, o: 2, ',': 1, ' ': 1, w: 1, r: 1, d: 1, '!': 1 }

In this implementation, we use a hash table countto record the number of occurrences of each character. For each character, we make it the key of the hash table and the number of times it occurs as the value of the hash table. If the character already exists in the hash table, add 1 to its corresponding value; otherwise, add the key in the hash table and set its value to 1. After the traversal is complete, the key-value pairs in the hash table represent the number of occurrences of each character in the string.

Guess you like

Origin blog.csdn.net/qq_43720551/article/details/131237626
Recommended