Group
Functions in C#
Objective
1. Write a function named "CountDV" that accepts a string and two reference variables to count the digits and vowels.
2. Loop through each character in the string to check if it is a digit or a vowel.
3. Update the reference variables for digits and vowels accordingly.
4. Return the count of digits and vowels through the reference parameters.
Write a C# function that calculates the amount of numeric digits and vowels that a text string contains. It will accept three parameters: the string that we want to search, the variable that returns the number of digits, and the number of vowels, in that order). The function should be called "CountDV". Use it like this:
CountDV ("This is the phrase 12", ref amountOfDigits, ref amountOfVowels)
In this case, amountOfDigits would be 2 and amountOfVowels would be 5
Example C# Exercise
Show C# Code
using System;
class Program
{
// Function to count the digits and vowels in a string
public static void CountDV(string text, ref int digits, ref int vowels)
{
// Initialize the counters for digits and vowels
digits = 0;
vowels = 0;
// Convert the text to lowercase to make vowel comparison easier
text = text.ToLower();
// Loop through each character in the string
foreach (char c in text)
{
// Check if the character is a digit
if (Char.IsDigit(c))
{
digits++; // Increment the digits counter
}
// Check if the character is a vowel
else if ("aeiou".Contains(c))
{
vowels++; // Increment the vowels counter
}
}
}
// Main method to test the CountDV function
public static void Main(string[] args)
{
// Initialize variables to store the results
int amountOfDigits = 0;
int amountOfVowels = 0;
// Call the CountDV function with a sample text
CountDV("This is the phrase 12", ref amountOfDigits, ref amountOfVowels);
// Output the results
Console.WriteLine("Number of digits: " + amountOfDigits);
Console.WriteLine("Number of vowels: " + amountOfVowels);
}
}
Output
Number of digits: 2
Number of vowels: 5