我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
var mainStr = "str1,str2,str3,str4";
我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。
我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。
我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
var mainStr = "str1,str2,str3,str4";
我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。
我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。
当前回答
我使用的是Node.js v.6.0.0,最快的是带索引的(Lo Sauer回答中的第三个方法)。
二是:
函数count(s, c) { Var n = 0; 对于(令x (s)) { 如果(x == c) n + +; } 返回n; }
其他回答
快速搜索谷歌得到了这个(从http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript)
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
像这样使用它:
test = 'one,two,three,four'
commas = test.count(',') // returns 3
我对接受的答案做了轻微的改进,它允许检查区分大小写/不区分大小写的匹配,并且是附加到字符串对象的方法:
String.prototype.count = function(lit, cis) {
var m = this.toString().match(new RegExp(lit, ((cis) ? "gi" : "g")));
return (m != null) ? m.length : 0;
}
Lit是要搜索的字符串(例如'ex'), cis是不区分大小写的,默认为false,它将允许选择不区分大小写的匹配。 要搜索字符串'I love StackOverflow.com'中的小写字母'o',你可以使用:
var amount_of_os = 'I love StackOverflow.com'.count('o');
Amount_of_os等于2。 如果我们再次使用不区分大小写的匹配来搜索相同的字符串,您将使用:
var amount_of_os = 'I love StackOverflow.com'.count('o', true);
这一次,amount_of_os将等于3,因为字符串中的大写O包含在搜索中。
下面是一个类似的解决方案,但它使用了Array.prototype.reduce
function countCharacters(char, string) {
return string.split('').reduce((acc, ch) => ch === char ? acc + 1: acc, 0)
}
如前所述,String.prototype.split的工作速度比String.prototype.replace快得多。
下面是最简单的逻辑,很容易理解
//Demo string with repeat char
let str = "Coffee"
//Splitted the str into an char array for looping
let strArr = str.split("")
//This below is the final object which holds the result
let obj = {};
//This loop will count char (You can also use traditional one for loop)
strArr.forEach((value,index)=>{
//If the char exists in the object it will simple increase its value
if(obj[value] != undefined)
{
obj[value] = parseInt(obj[value]) + 1;
}//else it will add the new one with initializing 1
else{
obj[value] =1;
}
});
console.log("Char with Count:",JSON.stringify(obj)); //Char with Count:{"C":1,"o":1,"f":2,"e":2}
我刚刚在repl上做了一个快速而肮脏的测试。它使用Node v7.4。对于单个字符,标准的For循环是最快的:
一些代码:
// winner!
function charCount1(s, c) {
let count = 0;
c = c.charAt(0); // we save some time here
for(let i = 0; i < s.length; ++i) {
if(c === s.charAt(i)) {
++count;
}
}
return count;
}
function charCount2(s, c) {
return (s.match(new RegExp(c[0], 'g')) || []).length;
}
function charCount3(s, c) {
let count = 0;
for(ch of s) {
if(c === ch) {
++count;
}
}
return count;
}
function perfIt() {
const s = 'Hello, World!';
const c = 'o';
console.time('charCount1');
for(let i = 0; i < 10000; i++) {
charCount1(s, c);
}
console.timeEnd('charCount1');
console.time('charCount2');
for(let i = 0; i < 10000; i++) {
charCount2(s, c);
}
console.timeEnd('charCount2');
console.time('charCount3');
for(let i = 0; i < 10000; i++) {
charCount2(s, c);
}
console.timeEnd('charCount3');
}
几次运行的结果:
perfIt()
charCount1: 3.301ms
charCount2: 11.652ms
charCount3: 174.043ms
undefined
perfIt()
charCount1: 2.110ms
charCount2: 11.931ms
charCount3: 177.743ms
undefined
perfIt()
charCount1: 2.074ms
charCount2: 11.738ms
charCount3: 152.611ms
undefined
perfIt()
charCount1: 2.076ms
charCount2: 11.685ms
charCount3: 154.757ms
undefined
更新2021年2月10日:修复了repl中的拼写错误。它演示
更新2020年10月24日:Node.js 12仍然是这样(你自己在这里玩)