我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
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个字符。
当前回答
更新06/10/2022
所以我运行了各种性能测试,如果你的用例允许的话,使用split似乎会表现得最好。
function countChar(char: string, string: string): number {
return string.split(char).length - 1
}
countChar('x', 'foo x bar x baz x')
我知道我来晚了,但我很困惑,没有人用最基本的方法来回答这个问题。社区对这个问题提供的大部分答案都是基于迭代的,但都是在每个字符的基础上移动字符串,这并不是真正有效的。
When dealing with a large string that contains thousands of characters walking over each character to get the occurance count can become rather extraneous not to mention a code-smell. The below solutions take advantage of slice, indexOf and the trusted traditional while loop. These approaches prevent us having to walk over each character and will greatly speed up the time it takes to count occurances. These follow similar logic to that you'd find in parsers and lexical analyzers that require string walks.
与Slice一起使用
在这种方法中,我们利用切片和每个indexOf匹配,我们将通过字符串移动我们的方式,并消除之前搜索的药水。每次调用indexOf,它搜索的字符串的大小都会变小。
function countChar (char: string, search: string): number {
let num: number = 0;
let str: string = search;
let pos: number = str.indexOf(char);
while(pos > -1) {
str = str.slice(pos + 1);
pos = str.indexOf(char);
num++;
}
return num;
}
// Call the function
countChar('x', 'foo x bar x baz x') // 3
使用IndexOf from position
类似于使用slice的第一种方法,但它不是扩大我们正在搜索的字符串,而是利用indexOf方法中的from参数。
function countChar (char: string, str: string): number {
let num: number = 0;
let pos: number = str.indexOf(char);
while(pos > -1) {
pos = str.indexOf(char, pos + 1);
num++;
}
return num;
}
// Call the function
countChar('x', 'foo x bar x baz x') // 3
就我个人而言,我倾向于第二种方法而不是第一种,但在处理大字符串和较小尺寸的字符串时,两者都很好且性能良好。
其他回答
var mainStr = “str1,str2,str3,str4”; var splitStr = mainStr.split(“,”).length - 1;减去 1 很重要! alert(splitStr);
分割成一个数组会给我们一些元素,这些元素总是比字符的实例数多1。这可能不是最有效的内存,但如果您的输入总是很小,这是一种直接且易于理解的方法。
如果您需要解析非常大的字符串(大于几百个字符),或者如果这是在处理大量数据的核心循环中,我会推荐不同的策略。
我使用的是Node.js v.6.0.0,最快的是带索引的(Lo Sauer回答中的第三个方法)。
二是:
函数count(s, c) { Var n = 0; 对于(令x (s)) { 如果(x == c) n + +; } 返回n; }
我正在做一个需要子字符串计数器的小项目。搜索错误的短语没有提供给我任何结果,然而在编写我自己的实现后,我偶然发现了这个问题。不管怎样,这是我的方法,它可能比这里的大多数慢,但可能对某些人有帮助:
function count_letters() {
var counter = 0;
for (var i = 0; i < input.length; i++) {
var index_of_sub = input.indexOf(input_letter, i);
if (index_of_sub > -1) {
counter++;
i = index_of_sub;
}
}
http://jsfiddle.net/5ZzHt/1/
请让我知道,如果你发现这个实现失败或不遵循一些标准!:)
更新 你可能想要替换:
for (var i = 0; i < input.length; i++) {
:
for (var i = 0, input_length = input.length; i < input_length; i++) {
上面讨论的内容很有趣: http://www.erichynds.com/blog/javascript-length-property-is-a-stored-value
这是我的解决方案。很多解决方案已经张贴在我之前。但我喜欢在这里分享我的观点。
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
下面是最简单的逻辑,很容易理解
//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}