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

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

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

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

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


当前回答

有一个非常棘手的方法,但它是相反的:

const sampleStringText = "/john/dashboard/language";

假设上面的例子,为了计算正斜杠的数量,你可以这样做:

console.log( sampleStringText.split('/') - 1 );

所以我建议使用函数(TypeScript):

const counter = (sentence: string, char: string): number => sentence.split(char) - 1;

其他回答

有:

function character_count(string, char, ptr = 0, count = 0) {
    while (ptr = string.indexOf(char, ptr) + 1) {count ++}
    return count
}

也适用于整数!

好吧,另一个用regexp的——可能不快,但比其他的更短,可读性更好,在我的例子中只是用“_”来计数

key.replace(/[^_]/g,'').length

只要删除所有不像你的char的东西 但是用字符串作为输入看起来不太好

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

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

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

我相信您会发现下面的解决方案非常短,非常快,能够处理非常长的字符串,能够支持多字符搜索,防错,并能够处理空字符串搜索。

function substring_count(source_str, search_str, index) {
    source_str += "", search_str += "";
    var count = -1, index_inc = Math.max(search_str.length, 1);
    index = (+index || 0) - index_inc;
    do {
        ++count;
        index = source_str.indexOf(search_str, index + index_inc);
    } while (~index);
    return count;
}

使用示例:

console.log(substring_count("Lorem ipsum dollar un sit amet.", "m ")) 函数substring_count(source_str, search_str, index) { Source_str += "", search_str += ""; var count = -1, index_inc = Math.max(search_str. var)长度,1); Index = (+ Index || 0) - index_inc; {做 + +计数; Index = source_str。indexOf(search_str, index + index_inc); } while (~index); 返回计数; }

上面的代码修复了Jakub Wawszczyk的主要性能错误,即使在indexOf说没有匹配之后,代码仍然在寻找匹配,而且他的版本本身也不能工作,因为他忘记给函数输入参数。