如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:
var temp = "This is a string.";
alert(temp.count("is")); //should output '2'
当前回答
//Try this code
const countSubStr = (str, search) => {
let arrStr = str.split('');
let i = 0, count = 0;
while(i < arrStr.length){
let subStr = i + search.length + 1 <= arrStr.length ?
arrStr.slice(i, i+search.length).join('') :
arrStr.slice(i).join('');
if(subStr === search){
count++;
arrStr.splice(i, search.length);
}else{
i++;
}
}
return count;
}
其他回答
只需编码打高尔夫球丽贝卡·切尔诺夫的解决方案:-)
alert(("This is a string.".match(/is/g) || []).length);
第二次迭代次数较少(仅当子字符串的第一个字母匹配时),但循环仍使用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 string='这是一个字符串',searchFor='is',计数=0,pos=string.indexOf(searchFor);而(位置>-1){++计数;pos=string.indexOf(searchFor,++pos);}console.log(计数);//2.
var mystring = 'This is the lorel ipsum text';
var mycharArray = mystring.split('');
var opArr = [];
for(let i=0;i<mycharArray.length;i++){
if(mycharArray[i]=='i'){//match the character you want to match
opArr.push(i);
}}
console.log(opArr); // it will return matching index position
console.log(opArr.length); // it will return length
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)