javascript - 我想使用 Switch 语句在 Javascript 中查找元音出现
问题描述
我想编写一个带有 switch 语句的函数来计算一行文本中任何两个元音连续出现的次数。例如,在句子中
例如:
原始字符串 = “请阅读此应用程序并感谢我”。
字符串ea, ea, ui 中出现这种情况。
输出:3
function findOccurrences() {
var str = "Pleases read this application and give me gratuity";
var count = 0;
switch (str) {
case 'a':
count++;
case 'A':
count++
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
return 1;
default:
return 0;
}
}
findOccurrences();
解决方案
您可以使用正则表达式来查找出现次数。
原始字符串:Pl ea ses r ea d this application and give me grat ui ty
出现:ea,ea,io,ui
结果:4
正则表达式:
[aeiou]
表示这些字符中的任何一个。{2}
正好 2 个({2,}
如果您想连续匹配 2 个或更多字符,请更改为)g
在第一场比赛后不要停止(gi
如果你想让它不区分大小写,请更改为)
function findOccurrences() {
var str = "Pleases read this application and give me gratuity";
var res = str.match(/[aeiou]{2}/g);
return res ? res.length : 0;
}
var found = findOccurrences();
console.log(found);
编辑:与switch
声明
function findOccurrences() {
var str = "Pleases read this application and give me gratuity";
var chars = str.toLowerCase().split("");
var count = 0;
// Loop over every character
for(let i = 0; i < chars.length - 1; i++) {
var char = chars[i];
var next = chars[i + 1];
// Increase count if both characters are any of the following: aeiou
if(isCorrectCharacter(char) && isCorrectCharacter(next)) {
count++
}
}
return count;
}
// Check if a character is any of the following: aeiou
function isCorrectCharacter(char) {
switch (char) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
var found = findOccurrences();
console.log(found);
推荐阅读
- reactjs - 运行 gzipped react 代码给出错误“Uncaught SyntaxError: Unexpected token '<”
- spring-boot - 在 Spring Boot 应用程序中以编程方式执行命令
- mysql - 从第二个表存储过程mysql中仅通过其ID选择一个图像
- reactjs - 如何在具有百分比和条件的反应挂钩中使用 useState?
- python - Python中elif语句的语法错误
- python - 布尔到数据框熊猫
- android - Swipable 在 Android 中不起作用(Expo Cli)
- python - pytorch CNN 模型中的 BatchNorm2d 错误
- python - 双向 LSTM 合并模式解释
- javascript - 从 msql 获取数据到 selectpickers 进行编辑