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

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

当前回答

/** Function that count occurrences of a substring in a string;
 * @param {String} string               The string
 * @param {String} subString            The sub string to search for
 * @param {Boolean} [allowOverlapping]  Optional. (Default:false)
 *
 * @author Vitim.us https://gist.github.com/victornpb/7736865
 * @see Unit Test https://jsfiddle.net/Victornpb/5axuh96u/
 * @see https://stackoverflow.com/a/7924240/938822
 */
function occurrences(string, subString, allowOverlapping) {

    string += "";
    subString += "";
    if (subString.length <= 0) return (string.length + 1);

    var n = 0,
        pos = 0,
        step = allowOverlapping ? 1 : subString.length;

    while (true) {
        pos = string.indexOf(subString, pos);
        if (pos >= 0) {
            ++n;
            pos += step;
        } else break;
    }
    return n;
}

用法

occurrences("foofoofoo", "bar"); //0

occurrences("foofoofoo", "foo"); //3

occurrences("foofoofoo", "foofoo"); //1

允许重叠

occurrences("foofoofoo", "foofoo", true); //2

比赛:

  foofoofoo
1 `----´
2    `----´

单元测试

https://jsfiddle.net/Victornpb/5axuh96u/

基准

我做了一个基准测试,我的功能超过了10倍比gumbo发布的regexp匹配函数更快。在我的测试中字符串长度为25个字符。字符“o”出现2次。我在Safari中执行了1000 000次。Safari 5.1基准>执行总时间:5617ms(正则表达式)基准测试>执行总时间:881毫秒(我的功能快6.4倍)Firefox 4基准>执行总时间:8547毫秒(Rexep)基准测试>总执行时间:634毫秒(我的功能更快13.5倍)编辑:我所做的更改缓存的子字符串长度为字符串添加了类型转换。添加了可选的“allowOverlapping”参数修复了“”空子字符串大小写的正确输出。

Gist

https://gist.github.com/victornpb/7736865

其他回答

太老了,但我今天需要做这样的事情,只想事后检查一下。对我来说工作很快。

String.prototype.count = function(substr,start,overlap) {
    overlap = overlap || false;
    start = start || 0;

    var count = 0, 
        offset = overlap ? 1 : substr.length;

    while((start = this.indexOf(substr, start) + offset) !== (offset - 1))
        ++count;
    return count;
};

看到这篇帖子。

let str = 'As sly as a fox, as strong as an ox';

let target = 'as'; // let's look for it

let pos = 0;
while (true) {
  let foundPos = str.indexOf(target, pos);
  if (foundPos == -1) break;

  alert( `Found at ${foundPos}` );
  pos = foundPos + 1; // continue the search from the next position
}

相同的算法可以被布置得更短:

let str = "As sly as a fox, as strong as an ox";
let target = "as";

let pos = -1;
while ((pos = str.indexOf(target, pos + 1)) != -1) {
  alert( pos );
}

添加了此优化:

如何计算字符串中的字符串出现次数?

这可能是这里最快的实现,但如果您将“++pos”替换为“pos+=searchFor.length”,则会更快汉森里克

function occurrences(str_, subStr) {
  let occurence_count = 0
  let pos = -subStr.length
  while ((pos = str_.indexOf(subStr, pos + subStr.length)) > -1) {
    occurence_count++
  }
  return occurence_count
}

这是我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(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性

 function substrCount( str, x ) {
   let count = -1, pos = 0;
   do {
     pos = str.indexOf( x, pos ) + 1;
     count++;
   } while( pos > 0 );
   return count;
 }