如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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.occurrencesOf = function(s, i) {
 return (n => (n === -1) ? 0 : 1 + this.occurrencesOf(s, n + 1))(this.indexOf(s, (i || 0)));
};

看到这篇帖子。

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 );
}

您可以使用match来定义这样的函数:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}

第二次迭代次数较少(仅当子字符串的第一个字母匹配时),但循环仍使用2:

   function findSubstringOccurrences(str, word) {
        let occurrences = 0;
        for(let i=0; i<str.length; i++){
            if(word[0] === str[i]){ // to make it faster and iterate less
                for(let j=0; j<word.length; j++){
                    if(str[i+j] !== word[j]) break;
                    if(j === word.length - 1) occurrences++;
                }
            }
        }
        return occurrences;
    }
    
    console.log(findSubstringOccurrences("jdlfkfomgkdjfomglo", "omg"));

var countInstances=函数(主体,目标){var全局计数器=0;var concatstring=“”;for(var i=0,j=target.length;i<body.length;i++){concatstring=body.substring(i-1,j);if(concatstring===目标){全局计数器+=1;concatstring='';}}返回全局计数器;};console.log(countInstance('abcabc','abc'));//==>2.console.log(countInstance('ababa','aba'));//==>2.console.log(countInstance('aaabbb','ab'));//==>1.