Sure, here is a Rust function to count the number of vowels in a given string:
Rust
fn count_vowels(str: &str) -> usize {
// Create a set of vowels.
let vowels = ['a', 'e', 'i', 'o', 'u'];
// Initialize a counter to track the number of vowels.
let mut count = 0;
// Iterate over the characters in the string.
for c in str.chars() {
// Check if the character is a vowel.
if vowels.contains(&c) {
// Increment the counter.
count += 1;
}
}
// Return the number of vowels.
return count;
}
fn main() {
let str = "hello";
let count = count_vowels(str);
println!("The number of vowels in the string is: {}", count);
}
This function first creates a set of vowels. The function then initializes a counter to track the number of vowels. The function then iterates over the characters in the string. For each character, the function checks if the character is a vowel. If the character is a vowel, the function increments the counter. Finally, the function returns the number of vowels.
To run this program, you can save it as a .rs file and then compile and run it using the following commands:
Code snippet
rustc count_vowels.rs
./count_vowels
This will print the following output:
Code snippet
The number of vowels in the string is: 2
This indicates that the string hello has 2 vowels.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust function to count the number of vowels in a given string:
Rust
This function first creates a set of vowels. The function then initializes a counter to track the number of vowels. The function then iterates over the characters in the string. For each character, the function checks if the character is a vowel. If the character is a vowel, the function increments the counter. Finally, the function returns the number of vowels.
To run this program, you can save it as a
.rsfile and then compile and run it using the following commands:Code snippet
This will print the following output:
Code snippet
This indicates that the string
hellohas 2 vowels.