Vowel counter
- Rust course
- Beginner
- Lesson 112/115
- 7 min
Write a program that counts vowels in a string.
Final task: vowel counter
In the final tasks of the beginner level you'll combine what you have learned. The first: counting the vowels and consonants in a text. What's needed: bringing letters to one form with to_lowercase, looping with chars(), classifying with match:
match c {
'a' | 'e' | 'ı' | 'i' | 'o' | 'ö' | 'u' | 'ü' => sesli += 1,
c if c.is_alphabetic() => sessiz += 1,
_ => {} // spaces, punctuation, digits
}Use a tuple to return the result as two values: -> (usize, usize).
Returning a tuple
The function returns two counters; on the caller's side they are unpacked with a tuple pattern:
fn say(s: &str) -> (usize, usize) {
let mut sesli = 0;
let mut sessiz = 0;
for c in s.to_lowercase().chars() {
// match ...
}
(sesli, sessiz)
}
let (a, b) = say("Merhaba Dünya!");to_lowercase() returns a new String; the loop runs over it.
Practice Count the letters
Write the function fn say(s: &str) -> (usize, usize): count the vowels (aeıioöuü) and the other alphabetic letters in the lowercased text. Print it as sesli: 5, sessiz: 7 for "Merhaba Dünya!".
Starter code
fn main() {
// buraya yaz
}Sample solution
fn say(s: &str) -> (usize, usize) {
let mut sesli = 0;
let mut sessiz = 0;
for c in s.to_lowercase().chars() {
match c {
'a' | 'e' | 'ı' | 'i' | 'o' | 'ö' | 'u' | 'ü' => sesli += 1,
c if c.is_alphabetic() => sessiz += 1,
_ => {}
}
}
(sesli, sessiz)
}
fn main() {
let (a, b) = say("Merhaba Dünya!");
println!("sesli: {}, sessiz: {}", a, b);
}Expected output
sesli: 5, sessiz: 7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is the <code>_ => {}</code> arm needed?
- For performance
- To count vowels
- It isn't needed
- match must be exhaustive; non-letter characters must fall into an arm too Correct answer
Explanation: Every possible char value must fit an arm; a guarded arm doesn't guarantee exhaustiveness.
2 Return a tuple
fn say(s: &str) -> ____ {
// ...
(sesli, sessiz)
}
fn say(s: &str) -> (usize, usize) {
// ...
(sesli, sessiz)
}
Explanation: The (usize, usize) tuple type is used to return two values.
3 Character and class
| Term | Meaning |
|---|---|
'ü' |
Vowel |
'ğ' |
Consonant |
' ' |
Not counted |
'!' |
Ignored |