Counting characters in a string is a common task in programming that can be both educational and useful. In this tutorial, we’ll be more specific and will walk through how to create a function to count the number of vowels in a given string. This guide is perfect for beginners and anyone looking to refresh their coding skills.
We’ll start by identifying the problem. Our function will be receiving a string, count how many characters a
, e
, i
, o
and u
are present and return that value. Seems easy, so let’s get to work.
I chose to use Javascript to solve this problem. You can use another language;; although the code will differ, the logic remains the same.
Begin by creating a JavaScript file. (I named mine index.js
but you can name yours however you want.)
Then, let’s start by step 1 of our plan; defining a function that takes a string as an input. Write the following code into your file.
We can implement steps 2 and 4 at the same time, since both involve the counter variable. Initialize a variable called counter
with a value of 0
and then return it.
Now we get to the best part, step 3.
First we’ll identify the characters we want to find (in our case are the vowels aeiou
) and assign them to a variable vowels
.
Then, since a string in Javascript is iterable, we can loop through each character in the input string and check if that character exists in vowels
.
The implemention of the function is almost complete; we just need to modify it for an edge case. What if the input string contains uppercase characters? The solution is simple: convert every character of the string to lowercase using the toLowerCase
method. Update the following highlighted line.
We are now ready to test our function. You can use different inputs to ensure it works as expected. Here are a few examples.
We got to the end of our post; let’s recap everything we’ve done:
countVowels
with a str
parameter;counter
set to 0;for ... of
loop to iterate through each character in the string;includes
method and incremented the counter if it is;counter
.