使用JavaScript计算字符串中每个字符的出现次数?
取一个数组来存储每个字符的频率。如果找到相似的字符,则加1,否则将1放入该数组。
假设以下是我们的字符串-
var sentence = "My name is John Smith";
以下是JavaScript代码以计算发生次数-
示例
var sentence = "My name is John Smith";sentence=sentence.toLowerCase();
var noOfCountsOfEachCharacter = {};
var getCharacter, counter, actualLength, noOfCount;
for (counter = 0, actualLength = sentence.length; counter <
actualLength; ++counter) {
getCharacter = sentence.charAt(counter);
noOfCount = noOfCountsOfEachCharacter[getCharacter];
noOfCountsOfEachCharacter[getCharacter] = noOfCount ? noOfCount + 1: 1;
}
for (getCharacter in noOfCountsOfEachCharacter) {
if(getCharacter!=' ')
console.log("Character="+getCharacter + " Occurrences=" +
noOfCountsOfEachCharacter[getCharacter]);
}
要运行以上程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo40.js。
输出结果
这将产生以下输出-
PS C:\Users\Amit\JavaScript-code> node demo40.jsCharacter=m Occurrences=3
Character=y Occurrences=1
Character=n Occurrences=2
Character=a Occurrences=1
Character=e Occurrences=1
Character=i Occurrences=2
Character=s Occurrences=2
Character=j Occurrences=1
Character=o Occurrences=1
Character=h Occurrences=2
Character=t Occurrences=1
以上是 使用JavaScript计算字符串中每个字符的出现次数? 的全部内容, 来源链接: utcz.com/z/331114.html