/*"
hi how are you i am fine thank you youtube am am ",
统计"you"出现的次数
*/
function wordCount(str, word) {
let arr = str.split(' ')
let count = 0
for (let i of arr) {
i === word ? count ++ : count
}
console.log(count) //2
return count
}
wordCount('hi how are you i am fine thank you youtube am','you')
/*"
hihowareyouiamfinethankyouyoutubeamam",
统计"you"出现的次数
没有空格
*/
function wordCount2(str, word) {
let ix = str.indexOf(word)
let count = 0
while (ix !== -1) {
count ++
str = str.substr(ix + word.length)
ix = str.indexOf(word)
}
console.log(count) //3 youtube
return count
}
wordCount2('hihowareyouiamfinethankyouyoutubeamam', 'you')