Count Vowels in a String
using System; public class StringUtilities { // Counts the number of vowels (a, e, i, o, u) in a given string. // The count is case-insensitive. public static int CountVowels(string text) { // Handle null or empty string input. if (string.IsNullOrEmpty(text)) { return 0; } int vo...
This C# code calculates the total number of vowels within a given string. It is designed to be case-insensitive, meaning both 'a' and 'A' are counted as vowels. This functionality is commonly used in text analysis, natur...
The `CountVowels` function iterates through each character of the input string `text`. It maintains a counter `vowelCount`, initialized to zero. For every character, it checks if it exists within a predefined string containing all lowercase and uppercase vowels (`"aeiouAEIOU"`). If a character is found in the vowel string, the `vowelCount` is incremented. The function handles edge cases by returning 0 if the input string is null or empty, preventing potential `NullReferenceException` or unnecessary iteration. The time complexity is O(n), where n is the length of the string, because each character is examined exactly once. The `string.Contains()` operation on a small, fixed-size string like `vowels` is effectively O(1). The space complexity is O(1) as it only uses a constant amount of extra space for variables. The algorithm is correct because it systematically checks every character against the complete set of vowels and correctly increments the count for each match.
function CountVowels(text): if text is null or empty: return 0 vowelCount = 0 vowels = "aeiouAEIOU" for each character `currentChar` in `text`: if `vowels` contains `currentChar`: increment `vowelCount` return `vowelCoun...