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

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

当前回答

此函数在三种模式下工作:查找字符串中单个字符的频率,查找字符串中相邻子字符串的频率,然后如果它与一个匹配,则会直接向前移动到它后面的下一个,第三个与前一个相似,但它也会计算给定字符串中的交叉子字符串

函数substringFrequency(字符串、子字符串、连接){let索引允许发生频率=0for(设i=0;i<string.length;i++){index=string.indexOf(substring,i)如果(索引!=-1){if((子字符串长度==1)||连接==true){i=索引}其他{i=索引+1}发生频率++}其他{打破} }return(发生频率)}console.log(substringFrequency('vvv','v'))console.log(substringFrequency('vvv','vv'))console.log(substringFrequency('vvv','vv'))

其他回答

String.prototype.Count=函数(查找){返回this.split(find).length-1;}console.log(“这是一个字符串。”.Count(“是”));

这将返回2。

正则表达式(global的缩写)中的g表示搜索整个字符串,而不仅仅是查找第一个出现的字符串。此匹配是两次:

var temp=“这是一个字符串。”;var count=(temp.match(/is/g)| |[]).length;console.log(计数);

如果没有匹配项,则返回0:

var temp=“Hello World!”;var count=(temp.match(/is/g)| |[]).length;console.log(计数);

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

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

没有人会看到这一点,但偶尔带回递归和箭头函数是很好的(双关语的意思很好)

String.prototype.occurrencesOf = function(s, i) {
 return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};