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

编程入门 行业动态 更新时间:2024-10-21 19:27:07
本文介绍了计算字符串中每个字符的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I want to count the number of occurrences of each character in a given string using JavaScript.

例如:

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

输出应为:

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

我试图搜索Google,但没有找到任何答案。我希望实现这个;订单无关紧要。

I tried searching Google, but didn't find any answer. I want to achieve something like this; order doesn't matter.

推荐答案

这在JavaScript(或任何其他支持地图的语言)中非常简单:

This is really, really simple in JavaScript (or any other language that supports maps):

// The string var str = "I want to count the number of occurances of each char in this string"; // A map (in JavaScript, an object) for the character=>count mappings var counts = {}; // Misc vars var ch, index, len, count; // Loop through the string... for (index = 0, len = str.length; index < len; ++index) { // Get this character ch = str.charAt(index); // Not all engines support [] on strings // Get the count for it, if we have one; we'll get `undefined` if we // don't know this character yet count = counts[ch]; // If we have one, store that count plus one; if not, store one // We can rely on `count` being falsey if we haven't seen it before, // because we never store falsey numbers in the `counts` object. counts[ch] = count ? count + 1 : 1; }

现在计数已每个角色的属性;每个属性的值是计数。您可以输出以下内容:

Now counts has properties for each character; the value of each property is the count. You can output those like this:

for (ch in counts) { console.log(ch + " count: " + counts[ch]); }

更多推荐

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

本文发布于:2023-11-29 20:34:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647557.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   字符   次数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!