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

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

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

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

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


当前回答

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与RegExp的性能

var i = 0; var split_start = new Date().getTime(); while (i < 30000) { "1234,453,123,324".split(",").length -1; i++; } var split_end = new Date().getTime(); var split_time = split_end - split_start; i= 0; var reg_start = new Date().getTime(); while (i < 30000) { ("1234,453,123,324".match(/,/g) || []).length; i++; } var reg_end = new Date().getTime(); var reg_time = reg_end - reg_start; alert ('Split Execution time: ' + split_time + "\n" + 'RegExp Execution time: ' + reg_time + "\n");

我刚刚在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仍然是这样(你自己在这里玩)

我的解决方案:

function countOcurrences(str, value){
   var regExp = new RegExp(value, "gi");
   return str.match(regExp) ? str.match(regExp).length : 0;  
}

下面是一个类似的解决方案,但它使用了Array.prototype.reduce

function countCharacters(char, string) {
  return string.split('').reduce((acc, ch) => ch === char ? acc + 1: acc, 0)
}

如前所述,String.prototype.split的工作速度比String.prototype.replace快得多。

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

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