问题
I want to write a function with a switch statement to count the number of occurrences of any two vowels in succession in a line of text. For example, in the sentence
For example:
Original string = “Pleases read this application and give me gratuity”.
Such occurrences in string ea, ea, ui.
Output: 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();
回答1:
If you insist on using switch you'd also need a loop and a flag to mark if you have seen a vowel already.
function findOccurrences() {
var str = "Pleases read this application and give me gratuity";
var count = 0;
let haveSeenVowel = false;
for (const letter of str.toLowerCase()) {
switch (letter) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
{
if (haveSeenVowel) {
count++;
haveSeenVowel = false;
} else {
haveSeenVowel = true;
}
break;
}
default:
haveSeenVowel = false
}
}
return count
}
console.log(findOccurrences());
回答2:
You can use a regex to find amount of occurrences.
Original string: Pleases read this application and give me gratuity
Occurences: ea, ea, io, ui
Result: 4
Regex:
[aeiou]
means any of these characters.{2}
exactly 2 of them (change to{2,}
if you wanna match 2 or more characters in a row)g
don't stop after the first match (change togi
if you want to make it case insensitive)
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);
EDIT: with switch
statement
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);
来源:https://stackoverflow.com/questions/62874483/i-want-to-find-vowel-occurences-in-javascript-using-switch-statement