我需要计算字符串中某个字符出现的次数。

例如,假设我的字符串包含:

var mainStr = "str1,str2,str3,str4";

我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。

我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。


当前回答

下面是最简单的逻辑,很容易理解

  //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}

其他回答

我用ramda js的解决方案:

const testString = 'somestringtotest'

const countLetters = R.compose(
  R.map(R.length),
  R.groupBy(R.identity),
  R.split('')
)

countLetters(testString)

链接到REPL。

我发现在非常大的字符串(例如,长度为1 000 000个字符)中搜索字符的最佳方法是使用replace()方法。

window.count_replace = function (str, schar) {
    return str.length - str.replace(RegExp(schar), '').length;
};

您还可以看到另一个JSPerf套件用于测试该方法以及在字符串中查找字符的其他方法。

至少有五种方法。最好的选项,也应该是最快的(由于本机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种方法的字符计数,所以我们可以直接汇集和分享我们的想法-只是为了好玩,也许一些有趣的基准:)

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函数。

这里有一个和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;
  }
}