Problem: Write a method that takes a string and returns the number of vowels in the string. You may assume that all the letters are lower cased. You can treat "y" as a consonant.
This question was a nice and easy surprise after the time conversion mayhem. It's pretty straight forward, but let me explain how I thought to solve this one. I want to be have a function take in a string, and no matter how it is written, I would like it all to be in lowercase (there's a method for that). Secondly, I would like every letter to be separated so that I can write a loop to go through each individually to see if it is any of the vowels. If it is, I'll have a vowel counter and it will go up by one and I will be happy.
1. Declare your function with one parameter.
function vowels(myString) {
}
}
2. Let's convert myString to all lower case and split all the letters apart. You can put it all in one statement. We can also set it equal to the same variable and we don't need to declare it with var, since it's already implicitly declared in the parameter. We also need to declare another variable, vowelCount, and set it equal to 0. This is the variable that will increase if the loop finds any vowels.
function vowels(myString) {
myString = myString.toLowerCase().split("");
var vowelCount = 0;
}
myString = myString.toLowerCase().split("");
var vowelCount = 0;
}
3. Now we just need a loop to go through all the letters individually.
function vowels(myString) {
myString = myString.toLowerCase().split("");
var vowelCount = 0;
for (var i = 0; i < myString.length; i++){
}
}
myString = myString.toLowerCase().split("");
var vowelCount = 0;
for (var i = 0; i < myString.length; i++){
}
}
4. If we were to put vowelCount++ as the code block for our loop, it would could every letter and increase the total by the wrong amount. We only need vowels, so we need an if statement. I know there's a shorter way of doing this, but I don't know what that is so this will have to do.
function vowels(myString) {
myString = myString.toLowerCase().split("");
var vowelCount = 0;
for (var i = 0; i < myString.length; i++){
if (myString[i] === "a" || myString[i] === "e" || myString[i] === "i" || myString[i] === "o" || myString[i] === "u" ||) {
vowelCount++;
}
}
return vowelCount;
}
myString = myString.toLowerCase().split("");
var vowelCount = 0;
for (var i = 0; i < myString.length; i++){
if (myString[i] === "a" || myString[i] === "e" || myString[i] === "i" || myString[i] === "o" || myString[i] === "u" ||) {
vowelCount++;
}
}
return vowelCount;
}
The last thing to do is return the vowelCount at the end there. Make sure you remember to do this outside of the for loop, right before you end the function.
Until next time!
Check out past problems here:
No comments :
Post a Comment