如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在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"));

其他回答

试试看

<?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>

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

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

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

参数:ustring:超集字符串countChar:子字符串

一个计算JavaScript中子字符串出现次数的函数:

函数subStringCount(ustring,countChar){var correspCount=0;var corresp=false;变量量=0;var prevChar=空;对于(var i=0;i!=ustring.length;i++){如果(ustring.charAt(i)==countChar.charAt(0)&&corresp==false){corresp=真;correspCount+=1;如果(correspCount==countChar.length){数量+=1;corresp=false;correspCount=0;}prevChar=1;}否则如果(ustring.charAt(i)==countChar.charAt(prevChar)&&corresp==true){correspCount+=1;如果(correspCount==countChar.length){数量+=1;corresp=false;correspCount=0;prevChar=空;}其他{prevChar+=1;}}其他{corresp=false;correspCount=0;}} 回报金额;}console.log(subStringCount(“Hello World,Hello World”,“ll”));

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

这将返回2。