我需要计算字符串中某个字符出现的次数。
例如,假设我的字符串包含:
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个字符。
当前回答
这里有一个和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;
}
}
其他回答
你也可以休息你的字符串,并像使用元素数组一样使用它
Array.prototype.filter ()
const mainStr = 'str1,str2,str3,str4'; const逗号=[…mainStr]。Filter (l => l === ',').length; console.log(逗号);
Or
Array.prototype.reduce ()
const mainStr = 'str1,str2,str3,str4'; const逗号=[…mainStr]。Reduce ((a, c) => c === ',' ?++a: a, 0); console.log(逗号);
简单地说,使用分割来找出字符串中某个字符出现的次数。
mainStr.split(" ")。Length //给出4,这是使用分隔符逗号分隔后的字符串数 mainStr.split(" ")。Length - 1 //给出3,这是逗号的计数
我刚刚在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仍然是这样(你自己在这里玩)
let str = "aabgrhaab"
let charMap = {}
for(let char of text) {
if(charMap.hasOwnProperty(char)){
charMap[char]++
} else {
charMap[char] = 1
}
}
console.log (charMap);//{a: 4, b: 2, g: 1, r: 1, h: 1}
那么string.split(desiredcharacter).length-1呢
例子:
Var STR = "hello is life"; Var len = str.split("h").length-1;将为上述字符串中的字符“h”提供计数2;