---
title: "Write a function to count the number of vowels in a given string in Rust."  
description: "Write a function to count the number of vowels in a given string in Rust."  
author: "Utpal Vishwas"  
published: 2023-06-20  
updated: 2023-06-23  
canonical: https://www.mindstick.com/forum/158801/write-a-function-to-count-the-number-of-vowels-in-a-given-string-in-rust  
category: "rust"  
tags: ["string", "programs", "rust"]  
reading_time: 2 minutes  

---

# Write a function to count the number of vowels in a given string in Rust.

Write a [function to count](https://www.mindstick.com/forum/158749/write-a-function-to-count-the-number-of-vowels-in-a-given-string) the number of vowels in a given [string](https://www.mindstick.com/articles/1527/string-split-in-c-sharp) in Rust.

## Replies

### Reply by Aryan Kumar

Sure, here is a Rust [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) to [count](https://www.mindstick.com/forum/157774/selecting-count-with-distinct) the number of vowels in a given string:

Rust

```plaintext
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

```plaintext
rustc count_vowels.rs
./count_vowels
```

This will print the following output:

Code snippet

```plaintext
The number of vowels in the string is: 2
```

This indicates that the string `hello` has 2 vowels.


---

Original Source: https://www.mindstick.com/forum/158801/write-a-function-to-count-the-number-of-vowels-in-a-given-string-in-rust

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
