简体   繁体   English

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

[英]Count the occurrence of every alphabet from a string in Javascript

I have seen similar questions like this asked before, such as counting characters in a given string.我以前见过类似的问题,例如计算给定字符串中的字符。 However when it comes to comparing given string to the letters of the alphabet and returning an object with occurences such as:但是,当将给定字符串与字母表中的字母进行比较并返回 object 时,会出现以下情况:

const letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

const sampleString = "a bee";

const results = {
 a: 1,
 b: 1,
 c: 0,
 d: 0,
 e: 2,
 f: 0,
 ...
}

I like using Object.fromEntries for this:我喜欢为此使用Object.fromEntries

 const sampleString = "a bee"; const result = Object.fromEntries(Array.from("abcdefghijklmnopqrstuvwxyz", ch => [ch, 0])); for (let ch of sampleString) if (ch in result) result[ch]++; console.log(result);

We can use Array.reduce() , to count letters in the sampleString.我们可以使用Array.reduce()来计算 sampleString 中的字母。

 const letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] const sampleString = "a bee"; const all = letters.reduce((acc, c) => (acc[c] = 0)); const result = [...sampleString].reduce((acc, c) => { if (c in acc) acc[c]++; return acc; }, letters.reduce((acc, c) => { acc[c] = 0; return acc; }, {}) ) console.log('Result:', result)
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Using Array.reduce and String.match may be an idea.使用Array.reduceString.match可能是一个想法。 So, for each letter of letters , use match (length) to determine the frequency of the letter in the given sample.因此,对于每个字母letters ,使用match (长度)来确定给定样本中字母的频率。

 const letters = `abcdefghijklmnopqrstuvwxyz`.split(``); const freq = (chr, sample) => (sample.match(RegExp(chr, `g`)) || []).length; const result = letters.reduce( (acc, chr) => ({...acc, [chr]: freq(chr, acc.sample)}), {sample: "a bee"}); console.log(result);

Or a more undestandable way或者更不可理喻的方式

const letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
const sampleString = "a bee";
results = {};
sampleString.forEach(letter=>{
   if(letters.includes(letter)) {
      if(results[letter] === undefined) results[letter]=0;
      results[letter]++;
   }
});

making the value as a key is a bad practice, because it will be hard to read, I recommend to call it what it is:将值作为键是一种不好的做法,因为它很难阅读,我建议将其命名为:

const letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
const tempString = "This is a string.";
let results = []
letters.forEach( char =>{
  const count = countCharacterOccurences(tempString, char)
  results.push({ alphabet: char, count })
})

function countCharacterOccurences(string, char) {
   return string.split(char).length - 1;
}

console.log(results)

//filter alphabet with value
const alphabetWithCount = results.filter( result => {
   return result.count > 0
})
console.log(alphabetWithCount)

//log alphabet only with counts
const alphabetOnlyWithCounts = alphabetWithCounts.map( alphabetWithCount => {
    return alphabetWithCount.alphabet
})

console.log(alphabetOnlyWithCounts)

//

You can apply .reduce() on the letters directly and in each iteration use RegExp() to replace all letters that do not match the current letter and the count the remaining letters in the string, if any, with .length :您可以将.reduce()直接应用于字母,并在每次迭代中使用RegExp()替换所有与当前letter不匹配的字母,并用.length计算字符串中剩余的字母(如果有):

 const letters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]; const sampleString = "a bee"; const results = letters.reduce((result,letter) => ({...result, [letter]: sampleString.replace(new RegExp(`[^${letter}]`,'g'), "").length }), {}); console.log( results );

NOTE :注意

Please note that:请注意:

sr.replace(new RegExp('[^a]','g'), "").length

for example, is equivalent to:例如,相当于:

sr.replace(/[^a]/g,"").length

See: JavaScript: How many times a character occurs in a string?请参阅: JavaScript:一个字符在字符串中出现多少次?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM