我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
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个字符。
当前回答
将此函数添加到sting prototype:
String.prototype.count=function(c) {
var result = 0, i = 0;
for(i;i<this.length;i++)if(this[i]==c)result++;
return result;
};
用法:
console.log("strings".count("s")); //2
其他回答
我发现在非常大的字符串(例如,长度为1 000 000个字符)中搜索字符的最佳方法是使用replace()方法。
window.count_replace = function (str, schar) {
return str.length - str.replace(RegExp(schar), '').length;
};
您还可以看到另一个JSPerf套件用于测试该方法以及在字符串中查找字符的其他方法。
这里有一个和split()和replace方法一样快的方法,它们比regex方法快一点点(在Chrome和Firefox中都是如此)。
let num = 0;
let str = "str1,str2,str3,str4";
//Note: Pre-calculating `.length` is an optimization;
//otherwise, it recalculates it every loop iteration.
let len = str.length;
//Note: Don't use a `for (... of ...)` loop, it's slow!
for (let charIndex = 0; charIndex < len; ++charIndex) {
if (str[charIndex] === ',') {
++num;
}
}
有一个非常棘手的方法,但它是相反的:
const sampleStringText = "/john/dashboard/language";
假设上面的例子,为了计算正斜杠的数量,你可以这样做:
console.log( sampleStringText.split('/') - 1 );
所以我建议使用函数(TypeScript):
const counter = (sentence: string, char: string): number => sentence.split(char) - 1;
这是我的解决方案。很多解决方案已经张贴在我之前。但我喜欢在这里分享我的观点。
const mainStr = 'str1,str2,str3,str4';
const commaAndStringCounter = (str) => {
const commas = [...str].filter(letter => letter === ',').length;
const numOfStr = str.split(',').length;
return `Commas: ${commas}, String: ${numOfStr}`;
}
// Run the code
console.log(commaAndStringCounter(mainStr)); // Output: Commas: 3, String: 4
这是我的REPL
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函数。