ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Count Vowels

Rust

Goal -- WPM

Ready
Exercise Algorithm Area
1fn count_vowels(s: &str) -> usize {
2let mut count = 0;
3for c in s.chars() {
4match c {
5'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U' => {
6count += 1;
7}
8_ => { /* Do nothing for non-vowels */ }
9}
10}
11count
12}
13
14fn main() {
15let text1 = "Hello World";
16println!("Vowels in '{}': {}", text1, count_vowels(text1));
17
18let text2 = "Rust Programming";
19println!("Vowels in '{}': {}", text2, count_vowels(text2));
20
21let text3 = "AEIOUaeiou";
22println!("Vowels in '{}': {}", text3, count_vowels(text3));
23
24let text4 = "rhythm";
25println!("Vowels in '{}': {}", text4, count_vowels(text4));
26
27let text5 = "";
28println!("Vowels in '{}': {}", text5, count_vowels(text5));
29}
Algorithm description viewbox

Count Vowels

Algorithm description:

This Rust function `count_vowels` calculates the total number of vowels (a, e, i, o, u, case-insensitive) present in an input string. It iterates through each character of the string and increments a counter if the character is a vowel. This is a fundamental string processing task, useful in natural language processing, text analysis, and basic data validation.

Algorithm explanation:

The `count_vowels` function iterates through each character of the input string `s` using `s.chars()`. For every character, it uses a `match` statement to check if the character is one of the ten vowels (five lowercase and five uppercase). If a character is a vowel, the `count` variable is incremented. The `_` arm of the `match` statement handles all other characters, doing nothing. The function returns the final `count`. The time complexity is O(n), where n is the length of the string, because each character is visited once. The space complexity is O(1) as it only uses a single counter variable.

Pseudocode:

function count_vowels(s):
  count = 0
  for each character c in s:
    if c is 'a' or 'e' or 'i' or 'o' or 'u' or 'A' or 'E' or 'I' or 'O' or 'U':
      increment count
  return count