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

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

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

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

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


当前回答

我正在做一个需要子字符串计数器的小项目。搜索错误的短语没有提供给我任何结果,然而在编写我自己的实现后,我偶然发现了这个问题。不管怎样,这是我的方法,它可能比这里的大多数慢,但可能对某些人有帮助:

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

其他回答

最简单的办法是…

的例子,

str = 'mississippi';

function find_occurences(str, char_to_count){
    return str.split(char_to_count).length - 1;
}

find_occurences(str, 'i') //outputs 4

我的解决方案:

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

更新:这可能是简单的,但它不是最快的。参见下面的基准测试。


令人惊讶的是,13年了,这个答案还没有出现。从直觉上看,它应该是最快的:

const s = "The quick brown fox jumps over the lazy dog.";
const oCount = s.length - s.replaceAll('o', '').length;

如果字符串中只有两种字符,那么这样仍然更快:


const s = "001101001";
const oneCount = s.replaceAll('0', '').length;

基准

const { performance } = require('node:perf_hooks');

const ITERATIONS = 10000000;
const TEST_STRING = "The quick brown fox jumps over the lazy dog.";

console.log(ITERATIONS, "iterations");

let sum = 0; // make sure compiler doesn't optimize code out
let start = performance.now();
for (let i = 0; i < ITERATIONS; ++i) {
  sum += TEST_STRING.length - TEST_STRING.replaceAll('o', '').length;
}
let end = performance.now();
console.log("  replaceAll duration", end - start, `(sum ${sum})`);

sum = 0;
start = performance.now();
for (let i = 0; i < ITERATIONS; ++i) {
  sum += TEST_STRING.split('o').length - 1
}
end = performance.now();
console.log("  split duration", end - start, `(sum ${sum})`);
10000 iterations
  replaceAll duration 2.6167500019073486 (sum 40000)
  split duration 2.0777920186519623 (sum 40000)
100000 iterations
  replaceAll duration 17.563208997249603 (sum 400000)
  split duration 8.087624996900558 (sum 400000)
1000000 iterations
  replaceAll duration 128.71587499976158 (sum 4000000)
  split duration 64.15841698646545 (sum 4000000)
10000000 iterations
  replaceAll duration 1223.3415840268135 (sum 40000000)
  split duration 629.1629169881344 (sum 40000000)

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

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

我对接受的答案做了轻微的改进,它允许检查区分大小写/不区分大小写的匹配,并且是附加到字符串对象的方法:

String.prototype.count = function(lit, cis) {
    var m = this.toString().match(new RegExp(lit, ((cis) ? "gi" : "g")));
    return (m != null) ? m.length : 0;
}

Lit是要搜索的字符串(例如'ex'), cis是不区分大小写的,默认为false,它将允许选择不区分大小写的匹配。 要搜索字符串'I love StackOverflow.com'中的小写字母'o',你可以使用:

var amount_of_os = 'I love StackOverflow.com'.count('o');

Amount_of_os等于2。 如果我们再次使用不区分大小写的匹配来搜索相同的字符串,您将使用:

var amount_of_os = 'I love StackOverflow.com'.count('o', true);

这一次,amount_of_os将等于3,因为字符串中的大写O包含在搜索中。