Daily Challenge #3 - Vowel Counter

thepracticaldev profile image dev.to staff ・1 min read

Hope you’re ready for another challenge! Let’s get started with Day 3.

Today’s challenge is modified from user @jayeshcp on CodeWars.

Write a function that returns the number (count) of vowels in a given string. Letters considered as vowels are: a, i, e, o, and u. The function should be able to take all types of characters as input, including lower case letters, upper case letters, symbols, and numbers.

In this challenge, you should be able to efficiently ignore spaces and symbols and discern between capital and lowercase letters. Beginners can start with only lowercase letters and move up from there. It’ll definitely get you ready for tomorrow.

Happy coding!~

Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!

Posted on by:

thepracticaldev profile

dev.to staff


The hardworking team behind dev.to ❤️


Editor guide



Demo on CodePen.


Nice solution, mine was similar in using regex match, but not as short. This one will error on a string without any vowels because match will return a null which doesn't have a length.


That's a good point. This could be avoided by checking if the result of the match is null and using an empty string instead. Something like this:


I also used template literals before the match so numeric values or null would be process too... and now the code is even uglier than before :P

Typo ${s}


Good catch! I corrected it. Thank you for letting me know!


I think this is the best solution if you're ok with regex.



Long Solution (my first solution)

def getVowelCount(str)
  vowels = ["a", "e", "i", "o", "u"]
  count = 0
  str.downcase.split('').each do |char|
    vowels.each do |vowel|
      char == vowel ? count += 1 : count += 0

Short Solution (my refactored solution)

def getVowelCount(str)

It would be interesting to know if str.count("aeiouAEIOU") was faster, or if reordering the letters to try to get the most likely match first was better – e.g. str.count("eiaouEIAOU")

const vowelString = 'whatever vowel string';
const count = [...(vowelString.toLowerCase())].map((letter) =>  [...'aeiou'].includes(letter) ? 1 : 0).reduce((aggr, curr) => aggr + curr);



Hi, i loved this solution. Took me a bit to get my head around the use of reduce here and it's awesome. Thanks. I learned something nice today.


Cool., I didn't know we can use spread on a string. 👍🏻


Thinking the string as a Set with O(1) for look up operations: solution is O(n), where n = len(str)

def count_vowels(str):
    vowels = "aeiouAEIOU"
    count = 0
    for c in str:
        if c in vowels:
            count += 1
    return count;

JS lambda way

conat vowels = new Set("aeiouAEIOU");
const counVowels = input => [...input].reduce((total, current) => (total += vowels.has(current)), 0);

My python solution!

def count_vowels(word):
    return len(l for l in word if l in "aeiou")

What if the word is in uppercase? Succinct though, my solution ended up like this:

import re

word = "sUpercalifragilisticexpialidocious"
def count_vowels(word):
    word = word.lower()
    letters = list(word)
    count = 0
    for letter in letters:
        if re.match("[aeiou]",letter):
            count += 1
    print count


import { compose } from 'crocks';

const toLowerCase = s => s.toLowerCase();
const spread = s => [...s];
const length = xs => xs.length;
const included = xs => x => xs.includes(x);
const filter = p => xs => xs.filter(p);

const charIncludesCount = chars => compose(

const vowelCount = charIncludesCount ('aeiou');

Oh I've been waiting for this one all morning! Decided I wanted to go all out on this on!

  • Rust
  • TDD
  • AND a Live Stream!

Come check it out while I work my way through this challenge! I'm live now and about to get started!



Here is my Rust solution all TDD'ed out!

extern crate lazy_static;

pub fn vowel_count(some_string: &str) -> usize {
    lazy_static! {
        static ref VOWELS: Vec<char> = vec!['a', 'e', 'i', 'o', 'u'];

        .filter(|c| VOWELS.contains(c))

mod tests {
    use crate::vowel_count;

    fn it_works_with_an_empty_string() {
        assert_eq!(vowel_count(""), 0);

    fn it_works_non_vowel_strings() {
        assert_eq!(vowel_count("d"), 0);
        assert_eq!(vowel_count("drthpCVM  *&^"), 0);
        assert_eq!(vowel_count("1234567890!@#$%^&*()--__+="), 0);
        assert_eq!(vowel_count("NPlkv.,<>?/"), 0);

    fn it_works_for_strings_of_just_vowels() {
        assert_eq!(vowel_count("a"), 1);
        assert_eq!(vowel_count("A"), 1);
        assert_eq!(vowel_count("AaeEiIoOuU"), 10);
        assert_eq!(vowel_count("eoiuioEAUIAEoieaiAoe"), 20);

    fn it_works_for_mixed_strings() {
        assert_eq!(vowel_count("deadpool"), 4);
            vowel_count("This is just a sentence! With some words and symbols #$%"),
        assert_eq!(vowel_count("TESTING OUT YELLING WITH ALL CAPS"), 9);
            vowel_count("!@#      \nThis is THE MOST COMPLICATED test SoO farrrr"),

I'm still live streaming as I type this out, but once I wrap up I'll post a link to the video here!


Ahhh! :panic:

Turns out OBS didn't want to behave for me today, and split my stream into 2 and dies before I finished, but we got almost all of it recorded! Learnings for next stream!

Links to the video that recorded for the longest here


Why not so simple as this (JS)...

const vowelsCounter = str => [...str].filter(l => 'aeiouAEIOU'.includes(l)).length;

Here is my try at it in JavaScript:

 * Count the number of vowels in the input and return an integer.
function countVowels (inputText) {
  // Create a regular expression that matches vowels. Look for all matches (g flag) and ignore case (i flag).
  const vowelRegularExpression = /[aeiou]/gi

  // Convert the input text to lower case and find the matches.
  const vowelMatches = inputText.match(vowelRegularExpression)

  // If there are matches, return the length of the match array. Otherwise, there were no matches, so return 0.
  return (vowelMatches ? vowelMatches.length : 0)

TI-Basic Calculator, where the string is in Ans:


And yes you can omit ending parens, which helps saves some bytes (:


Python regex example

import re
def num_vowels(s):
    return len(re.findall('[aeiou]', s))

JS one that's probably pretty speedy

vowelCount = string => {
  let count = 0,
  for (i = string.length; i > 0; ) {
    const c = string.charCodeAt(--i) & ~0x20; // that's a tilde btw
    count+=Number(c < 70 ? c == 69 || c == 65 : c == 73 || c == 79 || c == 85)
  return count;

Note that:

{E:'E'.charCodeAt(0), A:'A'.charCodeAt(0), I:'I'.charCodeAt(0), O:'O'.charCodeAt(0), U:'U'.charCodeAt(0)}

-> {E:69, A:65, I:73, O:79, U:85}

and vowels go pretty much eaiou in terms of how common they are in english.


JavaScript, using reduce:

function countVowels(string) {
    const vowels = 'aeiouAEIOU';
    return string.split('').reduce((counter, current) => {
        if(vowels.indexOf(current) != -1) {
            if(counter[current]) {
                counter[current] += 1;
            } else {
                counter[current] = 1;
        return counter;
    }, {});

console.log(countVowels('How much wood would a woodchuck chuck if a woodchuck could chuck wood?'));

// { o: 11, u: 7, a: 2, i: 1 }

This is my solution in Swift (with an extension 😊) :

extension String {
    func numberOfVowels() -> Int {
        var count = 0
        let vowels: [Character] = ["a","e","i","o", "u", "y"]

        self.lowercased().forEach { char in
            if vowels.contains(char) {
                count += 1

        return count
const charCounter = ({strToCount = "", chars = ""} = {}) => {
    const charsToCount = chars.toLowerCase();
    return Array.from(strToCount.toLowerCase())
        .reduce((acc, candidate) => acc += charsToCount.includes(candidate) 
        ? 1 : 0, 0)

const countVowels= strToCount => charCounter({strToCount, chars: "aeiou"});

assert(countVowels("The quick brown fox jumps over the lazy dog.") === 11);
assert(countVowels("Hello") === 2);
assert(countVowels("Xyl") === 0);
assert(countVowels("aeiouAEIOU") === 10);

Here is my simple solution with PHP:

function getCount($str) {
  $vowelsCount = 0;

  $vowels = ['a', 'e', 'i', 'o', 'u'];

  $index = 0;
  for(; $index < mb_strlen($str); $index++) {
    if (in_array($str[$index], $vowels)) {
      $vowelsCount += 1;

  return $vowelsCount;

Could also

const compose = (...fns) => fns.reduce((f, g) => (...args) => (f(g(...args)));
const test = require('./tester');
const vowelCount = str => String(str)
    .filter(ch => 'aeiou'.indexOf(ch) > -1)

test(vowelCount, [
        in: ["Hello O'Henry !"],
        out: 4,
        in: ['gnsp'],
        out: 0

This is very easy in Perl, as the transliteration operator returns the number of matches:

sub vowel_count2 { shift =~ tr/aeiouAEIOU// }

One can also use the Saturn (or Goatse) "secret" operator with a regex match:

sub vowel_count { my $count =()= shift =~ /[aeiou]/gi }

The global match returns all the matches in list context, the assignment to () enforces list context, and enforcing scalar context on it by a scalar assignment returns the number of elements.



  public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Type the word:");
        String word = scan.nextLine();

        String[] letters = word.split("");
        int count = 0;

        for (String l : letters) {
            if (l.matches("[aeiouAEIOU]")) {
                count += 1;

        System.out.println("The number of vowels is: " + count);

module Vowels (countVowels) where

import Data.Char (toUpper)

isVowel :: Char -> Bool
isVowel = flip elem "AEIOU"

countChar :: Char -> Integer
countChar letter = if isVowel letter 1 else 0

countVowels :: String -> Integer
countVowels = sum . map (countChar . toUpper)

Will have to double check the syntax (on Mobile) but I think this will work


In go!

func countVowels(s string) int {
    l := strings.ToLower(s)
    count := 0
    for _, c := range l {
        switch c {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
    return count

Go playground example

Uses fallthrough mostly because I wanted to, count++ would be smaller, but all cases behave the same (also its more easily maintainable).



static function vowels(s:String):Int {
  var vowels = 0;
  for (i in 0...s.length) {
    switch (s.charAt(i)) {
      case 'a' | 'A' | 'e' | 'E' | 'i' | 'I' | 'o' | 'O' | 'u' | 'U':
  return vowels;

iterators library looked useful but you can't fold an iterator, only an iterable, disappoint.

You also have to traverse the tree to get to the next letter. But I see what you mean. Only counting equality checks, hard-coding behaves like a linear search. My bad.

I think you might still be missing Brian's point that a hash set has O(1) lookup time, which is faster than the tree set's O(log n).

(On paper. Real-world implementations vary. e.g. Ruby's hashes just do linear search at this size.)


My solution is a bit longer because I don't know regex, but it gets the job done.


const countVowels = text => {
  let count = 0;
  text.toLowerCase().split("").forEach(char => {
    if (char === "a" || char === "e" || char === "i" || char === "o" || char === "u")
  return count;



from unicode import toLower

proc countVowels(input: string): int =
  for i in toLower(input):
    if i in "aeiou":
      result += 1

if isMainModule:
  const input = "@PPLes!43"

  echo countVowels(input)
use regex::Regex;

fn main() {
    let re = Regex::new(r"[aeiou]").unwrap();
    let mut result: i32 = 0;
    for _mat in re.find_iter("Hello, world!") {
        result += 1;
    println!("Vowel count: {:?}", result)

Link to playground - play.rust-lang.org/?version=stable...


A solution in Elixir

defmodule VowelCounter do
  @vowels ~r/(a|e|i|o|u)/i
  def count(""), do: 0

  def count(string) do
    |> Regex.scan(string)
    |> Enum.count() 


def removeAccents(str)
    accents = {
        ['á','à','â','ä','ã'] => 'a',
        ['é','è','ê','ë'] => 'e',
        ['í','ì','î','ï'] => 'i',
        ['ó','ò','ô','ö','õ'] => 'o',
        ['ú','ù','û','ü'] => 'u'
      accents.each do |ac,rep|
        ac.each do |s|
          str = str.gsub(s, rep)
      str = str.gsub(/[^a-zA-Z0-9\. ]/,"")
      str = str.gsub(/[ ]+/," ")
  str = str.gsub(/ /,"-")
  return str

def verifyVowels(texto)
    allLc = removeAccents(texto.downcase);
    countVowels = 0;
    allLc.split("").each do |letra|
        if (letra == 'a') | (letra == 'e') | (letra == 'i') | (letra == 'o') | (letra == 'u')
            countVowels+= 1;
    return countVowels
function countVowels(string) {
  if(typeof(string) !== 'string')
    throw new Error('input must be a string');

  const vowels = 'aeiouAEIOU';
  let vowelCount = 0;

  for(index in string) {
  return vowelCount;

ledgible I hope