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

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

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

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

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


当前回答

var mainStr = “str1,str2,str3,str4”; var splitStr = mainStr.split(“,”).length - 1;减去 1 很重要! alert(splitStr);

分割成一个数组会给我们一些元素,这些元素总是比字符的实例数多1。这可能不是最有效的内存,但如果您的输入总是很小,这是一种直接且易于理解的方法。

如果您需要解析非常大的字符串(大于几百个字符),或者如果这是在处理大量数据的核心循环中,我会推荐不同的策略。

其他回答

我更新了这个答案。我更喜欢使用火柴的想法,但它更慢:

console.log((“str1,str2,str3,str4”.match(/,/g) ||[]).长度);日志 3 console.log((“str1,str2,str3,str4”.match(new RegExp(“str”, “g”)) ||[]).长度);日志 4

如果事先知道要搜索什么,可以使用正则表达式文字;如果不知道,可以使用RegExp构造函数,并传入g标志作为参数。

匹配结果为空,因此|| []

以下是我在2009年给出的原始答案。它创建了一个不必要的数组,但是使用分割更快(截至2014年9月)。我很矛盾,如果我真的需要速度,毫无疑问我会使用分拆,但我更喜欢使用匹配。

旧答案(2009年):

如果你在找逗号:

(mainStr.split(",").length - 1) //3

如果你在找str

(mainStr.split("str").length - 1) //4

在@Lo的回答和我自己的愚蠢的性能测试中,分裂在速度上领先,至少在Chrome中,但再次创建额外的数组似乎不理智。

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

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

简单地说,使用分割来找出字符串中某个字符出现的次数。

mainStr.split(" ")。Length //给出4,这是使用分隔符逗号分隔后的字符串数 mainStr.split(" ")。Length - 1 //给出3,这是逗号的计数

Leo Sauers回答中的第五种方法失败,如果字符位于字符串的开头。 如。

var needle ='A',
  haystack = 'AbcAbcAbc';

haystack.split('').map( function(e,i){ if(e === needle) return i;} )
  .filter(Boolean).length;

将给出2而不是3,因为过滤函数布尔为0给出false。

其他可能的过滤功能:

haystack.split('').map(function (e, i) {
  if (e === needle) return i;
}).filter(function (item) {
  return !isNaN(item);
}).length;

还有一个答案:

function count(string){
  const count={}
  
  string.split('').forEach(char=>{
    count[char] = count[char] ? (count[char]+1) : 1;
  })
  
  return count
}

console.log(count("abfsdfsddsfdfdsfdsfdsfda"))

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

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说没有匹配之后,代码仍然在寻找匹配,而且他的版本本身也不能工作,因为他忘记给函数输入参数。