tommy-3

Posted on

# Learning Algorithms with JS, Python and Java #11: Count the Vowels

This series of articles follows Stephen Grider's Udemy course in three different languages.

Today's question is a simple introduction to regular expressions.

--- Directions
Write a function that returns the number of vowels
used in a string. Vowels are the characters 'a', 'e'
'i', 'o', and 'u'.
--- Examples
vowels('Hi There!') --> 3
vowels('Why do you ask?') --> 4
vowels('Why?') --> 0

# 1: Iterative Solution

JavaScript:

``````function vowels(str) {
let count = 0;
let checker = ['a', 'e', 'i', 'o', 'u'];
for (char of str.toLowerCase()) {
if (checker.includes(char)) {
count++;
}
}
return count;
}
``````

Python:

``````def vowels(string):
count = 0
checker = ['a', 'e', 'i', 'o', 'u']
for char in string.lower():
if char in checker:
count += 1
return count

``````

Java:

``````import java.util.Arrays;
import java.util.List;

static int vowels(String str) {
int count = 0;
List<Character> checker = Arrays.asList('a', 'e', 'i', 'o', 'u');
for (char chr : str.toLowerCase().toCharArray()) {
if (checker.contains(chr)) {
count++;
}
}
return count;
}
``````

# 2: Using Regular Expression

JavaScript:

``````function vowels(str) {
const matches = str.match(/[aeiou]/gi); // an array or null
return matches ? matches.length : 0;
}
``````

Python:

``````import re

def vowels(string):
matches = re.findall('[aeiou]', string, re.IGNORECASE)  # a list
return len(matches)

``````

Java:

``````import java.util.regex.Matcher;
import java.util.regex.Pattern;

static int vowels(String str) {
Pattern pattern = Pattern.compile("[aeiou]", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
``````

Java 9+:

``````import java.util.regex.Pattern;

static long vowels(String str) {
return Pattern.compile("[aeiou]", Pattern.CASE_INSENSITIVE)
.matcher(str)
.results()
.count();
}
``````