---
title: "Write a function to count the number of vowels in a given string."  
description: "Write a function to count the number of vowels in a given string."  
author: "Utpal Vishwas"  
published: 2023-06-14  
updated: 2023-06-15  
canonical: https://www.mindstick.com/forum/158749/write-a-function-to-count-the-number-of-vowels-in-a-given-string  
category: "c#"  
tags: ["c#", "string", "programs"]  
reading_time: 2 minutes  

---

# Write a function to count the number of vowels in a given string.

Write a [function to count](https://www.mindstick.com/forum/158801/write-a-function-to-count-the-number-of-vowels-in-a-given-string-in-rust) the number of vowels in a given string.

## Replies

### Reply by Aryan Kumar

Sure, here is the C# code to write a [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:

C#

```plaintext
using System;

public class Vowels
{
    public static int CountVowels(string str)
    {
        int vowelCount = 0;
        foreach (char ch in str)
        {
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
            {
                vowelCount++;
            }
        }
        return vowelCount;
    }

    public static void Main(string[] args)
    {
        string str = "Hello, world!";
        int vowelCount = CountVowels(str);
        Console.WriteLine("The number of vowels in the string is: {0}", vowelCount);
    }
}
```

This function first creates a variable called vowelCount and initializes it to 0. Then, it iterates through all the characters in the string. For each character, the function checks if the character is a vowel. If it is, then the function increments the value of vowelCount by 1. Finally, the function returns the value of vowelCount. The Main() method then calls the CountVowels() function to count the number of vowels in the string. The result is then printed to the console.


---

Original Source: https://www.mindstick.com/forum/158749/write-a-function-to-count-the-number-of-vowels-in-a-given-string

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
