我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
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个字符。
当前回答
最快的方法似乎是通过索引操作符:
函数特征(str, char) } 对于(var c = 0, i = 0, len = str.length;我< len;+ + i) } if (str[i] == char) } c + +; } } return c; } console.log(charOccurances('example/path/script.js', '/'));/ / 2
或者作为原型函数:
String.prototype.charOccurances =函数(char) } 对于(var c = 0, i = 0, len = this.length;我< len;+ + i) } if (this[i] == char) } c + +; } } return c; } console.log('example/path/script.js'. charoccurances ('/'));/ / 2
其他回答
下面是最简单的逻辑,很容易理解
//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}
String.prototype.reduce = Array.prototype.reduce; String.prototype.count =函数(c) { 返回。Reduce (((n, x) => n + (x === c ?)1: 0)), 0) }; Const n = "bugs bunny was here".count("b") console.log (n)
类似于基于上面的原型,但没有为字符串分配数组。分配几乎是上面每个版本的问题,除了循环变量。这避免了循环代码,重用了浏览器实现的数组。reduce函数。
简单地说,使用分割来找出字符串中某个字符出现的次数。
mainStr.split(" ")。Length //给出4,这是使用分隔符逗号分隔后的字符串数 mainStr.split(" ")。Length - 1 //给出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包含在搜索中。
至少有五种方法。最好的选项,也应该是最快的(由于本机RegEx引擎)被放在顶部。
方法1
("this is foo bar".match(/o/g)||[]).length;
// returns 2
方法2
"this is foo bar".split("o").length - 1;
// returns 2
不建议拆分,因为它是资源饥渴的。它为每个匹配分配新的“Array”实例。不要通过FileReader尝试>100MB文件。你可以观察确切的资源使用使用Chrome的分析器选项。
方法3
var stringsearch = "o"
,str = "this is foo bar";
for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) );
// returns 2
方法4
搜索单个字符
var stringsearch = "o"
,str = "this is foo bar";
for(var i=count=0; i<str.length; count+=+(stringsearch===str[i++]));
// returns 2
方法5
元素映射和过滤。不建议这样做,因为它的整体资源预分配,而不是使用python的“生成器”:
var str = "this is foo bar"
str.split('').map( function(e,i){ if(e === 'o') return i;} )
.filter(Boolean)
//>[9, 10]
[9, 10].length
// returns 2
分享: 我做了这个要点,目前有8种方法的字符计数,所以我们可以直接汇集和分享我们的想法-只是为了好玩,也许一些有趣的基准:)