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

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

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

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

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


当前回答

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

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包含在搜索中。

其他回答

下面使用正则表达式测试长度。Testex确保不存在16个或更多的连续非逗号字符。如果它通过了测试,那么它将继续拆分字符串。计算逗号的数量就像计算符号减1一样简单。

var mainStr = "str1,str2,str3,str4";
var testregex = /([^,]{16,})/g;
if (testregex.test(mainStr)) {
  alert("values must be separated by commas and each may not exceed 15 characters");
} else {
  var strs = mainStr.split(',');
  alert("mainStr contains " + strs.length + " substrings separated by commas.");
  alert("mainStr contains " + (strs.length-1) + " commas.");
}

该函数以字符串str作为参数,并计算字符串中每个唯一字符的出现次数。结果是每个字符的键值对。

var charFoundMap = {};//object defined
    for (var i = 0; i < str.length; i++) {

       if(!charFoundMap[ str[i] ])  {
        charFoundMap[ str[i] ]=1;
       } 
       else
       charFoundMap[ str[i] ] +=1;
       //if object does not contain this 
    }
    return charFoundMap;

} 

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

我知道这可能是一个老问题,但我有一个简单的解决方案为低水平的JavaScript初学者。

作为一个初学者,我只能理解这个问题的一些解决方案,所以我使用了两个嵌套的FOR循环来检查字符串中的每个字符,为每个发现等于该字符的字符增加一个计数变量。

我创建了一个新的空白对象,其中每个属性键是一个字符,值是每个字符在字符串中出现的次数(count)。

例子函数:

function countAllCharacters(str) {
  var obj = {};
  if(str.length!==0){
    for(i=0;i<str.length;i++){
      var count = 0;
      for(j=0;j<str.length;j++){
        if(str[i] === str[j]){
          count++;
        }
      }
      if(!obj.hasOwnProperty(str[i])){
        obj[str[i]] = count;
      }
    }
  }
  return obj;
}