如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:

var temp = "This is a string.";
alert(temp.count("is")); //should output '2'

当前回答

这是最快的功能!

为什么速度更快?

不逐个字符检查(有1个例外)使用while并增加1个var(字符计数var),而不是for循环检查长度并增加2个var(通常是var i和一个带有字符计数的var)使用WAY less vars不使用正则表达式!使用(希望)高度优化的函数所有操作都尽可能地组合在一起,避免了由于多次操作而导致的速度减慢String.product.timesCharExist=函数(c){var t=0,l=0,c=(c+“”)[0];while(l=this.indexOf(c,l)+1)++t;return t};

以下是一个更慢、更可读的版本:

    String.prototype.timesCharExist = function ( chr ) {
        var total = 0, last_location = 0, single_char = ( chr + '' )[0];
        while( last_location = this.indexOf( single_char, last_location ) + 1 )
        {
            total = total + 1;
        }
        return total;
    };

由于计数器、长的var名称和对1var的误用,这个速度较慢。

要使用它,只需执行以下操作:

    'The char "a" only shows up twice'.timesCharExist('a');

编辑:(2013/12/16)

不要与Opera 12.16或更高版本一起使用!它将比正则表达式解决方案花费几乎2.5倍的时间!

在chrome上,对于1000000个字符,此解决方案需要14ms到20ms。

相同量的regex溶液需要11-14ms。

使用函数(String.prototype外部)大约需要10-13ms。

以下是使用的代码:

    String.prototype.timesCharExist=function(c){var t=0,l=0,c=(c+'')[0];while(l=this.indexOf(c,l)+1)++t;return t};

    var x=Array(100001).join('1234567890');

    console.time('proto');x.timesCharExist('1');console.timeEnd('proto');

    console.time('regex');x.match(/1/g).length;console.timeEnd('regex');

    var timesCharExist=function(x,c){var t=0,l=0,c=(c+'')[0];while(l=x.indexOf(c,l)+1)++t;return t;};

    console.time('func');timesCharExist(x,'1');console.timeEnd('func');

所有解决方案的结果应该是100000!

注意:如果您希望此函数计数超过1个字符,请将其中的c=(c+“”)[0]更改为c=c+“”

其他回答


subst_count从php转换为Javascript


Locutus(将Php翻译为JS的包)subst_count(官方页面,代码复制如下)

function substr_count (haystack, needle, offset, length) { 
  // eslint-disable-line camelcase
  //  discuss at: https://locutus.io/php/substr_count/
  // original by: Kevin van Zonneveld (https://kvz.io)
  // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
  // improved by: Brett Zamir (https://brett-zamir.me)
  // improved by: Thomas
  //   example 1: substr_count('Kevin van Zonneveld', 'e')
  //   returns 1: 3
  //   example 2: substr_count('Kevin van Zonneveld', 'K', 1)
  //   returns 2: 0
  //   example 3: substr_count('Kevin van Zonneveld', 'Z', 0, 10)
  //   returns 3: false

  var cnt = 0

  haystack += ''
  needle += ''
  if (isNaN(offset)) {
    offset = 0
  }
  if (isNaN(length)) {
    length = 0
  }
  if (needle.length === 0) {
    return false
  }
  offset--

  while ((offset = haystack.indexOf(needle, offset + 1)) !== -1) {
    if (length > 0 && (offset + needle.length) > length) {
      return false
    }
    cnt++
  }

  return cnt
}

查看Locutus对Php的subst_count函数的翻译

无正则表达式的简单版本:

var temp=“这是一个字符串。”;var计数=(临时拆分('is').长度-1);警报(计数);

这是我2022年使用map()和filter()的解决方案:

string = "Xanthous: A person with yellow hair. Her hair was very xanthous in colour."       
count = string.split('').map((e,i) => { if(e === 'e') return i;}).filter(Boolean).length

只是为了使用这些功能的乐趣。该示例计算字符串中“e”的数量。

这与使用match()函数相同:

(string.match(/e/g)||[]).length

或者简单地使用split()函数:

string.split('e').length - 1

我认为最好的方法是使用match(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性

var temp=“这是一个字符串。”;console.log((temp.match(新RegExp(“is”,“g”))||[]).length);

对于将来找到此线程的任何人,请注意,如果您对其进行概括,则接受的答案不会总是返回正确的值,因为它会阻塞正则表达式运算符,如$和。。这里有一个更好的版本,可以处理任何针头:

function occurrences (haystack, needle) {
  var _needle = needle
    .replace(/\[/g, '\\[')
    .replace(/\]/g, '\\]')
  return (
    haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
  ).length
}