Sure, here is the C# code to write a function to count the number of vowels in a given string:
C#
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.
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 the C# code to write a function to count the number of vowels in a given string:
C#
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.