如果检查字符串“school”中字符“o”的出现次数,结果是 2。
示例 1:使用 for 循环检查字符出现次数
// program to check the number of occurrence of a character
function countString(str, letter) {
let count = 0;
// looping through the items
for (let i = 0; i < str.length; i++) {
// check if the character is at that position
if (str.charAt(i) == letter) {
count += 1;
}
}
return count;
}
// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');
//passing parameters and calling the function
const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
输出
Enter a string: school Enter a letter to check: o 2
在上面的示例中,会提示用户输入一个字符串和要检查的字符。
- 开始时,count 变量的值为 0。
- 使用 for 循环遍历字符串。
charAt()
方法返回指定索引处的字符。- 在每次迭代中,如果该索引处的字符与要匹配的字符匹配,则 count 变量会增加 1。
示例 2:使用正则表达式检查字符出现次数
// program to check the occurrence of a character
function countString(str, letter) {
// creating regex
const re = new RegExp(letter, 'g');
// matching the pattern
const count = str.match(re).length;
return count;
}
// take input from the user
const string = prompt('Enter a string: ');
const letterToCheck = prompt('Enter a letter to check: ');
//passing parameters and calling the function
const result = countString(string, letterToCheck);
// displaying the result
console.log(result);
输出
Enter a string: school Enter a letter to check: o 2
在上面的示例中,使用正则表达式 (regex) 来查找字符串的出现次数。
const re = new RegExp(letter, 'g');
创建一个正则表达式。match()
方法返回一个包含所有匹配项的数组。这里,str.match(re);
返回 ["o", "o"]。length
属性给出数组元素的长度。