DEV Community

tommy-3
tommy-3

Posted on

3 3

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();
}

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay