Rust
Vowel counter
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.
Exercise 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!".
Show example 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);
}
Test yourself
-
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
Show answer
match must be exhaustive; non-letter characters must fall into an arm too — Every possible char value must fit an arm; a guarded arm doesn't guarantee exhaustiveness.
-
Return a tuple
fn say(s: &str) -> ____ {
// ...
(sesli, sessiz)
}
Show answer
fn say(s: &str) -> (usize, usize) {
// ...
(sesli, sessiz)
}
-
Character and class
- 'ü'
- Vowel
- 'ğ'
- Consonant
- ' '
- Not counted
- '!'
- Ignored
Next lesson: Average calculator