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

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

当前回答

第二次迭代次数较少(仅当子字符串的第一个字母匹配时),但循环仍使用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"));

其他回答

正则表达式(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(计数);

你可以试试这个

let count = s.length - s.replace(/is/g, "").length;

函数countInstance(字符串,单词){返回字符串.split(word).length-1;}console.log(countInstance(“This is a string”,“is”))

试试看

<?php 
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>

<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);  
alert(count.length);
</script>
const getLetterMatchCount = (guessedWord, secretWord) => {
  const secretLetters = secretWord.split('');
  const guessedLetterSet = new Set(guessedWord);
  return secretLetters.filter(letter => guessedLetterSet.has(letter)).length;
};
const str = "rahul";
const str1 = "rajendra";

getLetterMatchCount(str, str1)