📌  相关文章
📜  C# 程序计算给定字符串中元音和辅音的数量(1)

📅  最后修改于: 2023-12-03 14:39:47.553000             🧑  作者: Mango

C#程序计算给定字符串中元音和辅音的数量

本文将介绍如何使用C#编写一个程序,用于计算给定字符串中元音和辅音的数量。程序将接受一个字符串作为输入,并统计该字符串中元音和辅音的数量。在程序开发过程中,我们将使用C#语言的字符串操作和循环控制语句。

实现思路
  1. 定义一个函数CountVowelsAndConsonants,该函数将接受一个字符串作为参数并返回一个包含元音和辅音数量的数组。
  2. 初始化元音计数器vowelCount为0,辅音计数器consonantCount为0。
  3. 使用foreach循环遍历字符串中的每个字符。
  4. 在循环中,使用switch语句判断当前字符是否为元音或辅音。如果是元音,则将vowelCount增加1;如果是辅音,则将consonantCount增加1。
  5. 返回包含vowelCountconsonantCount的数组。

下面是完整的C#代码实现:

using System;

class Program
{
    static void Main(string[] args)
    {
        string inputString = "Hello World";
        int[] counts = CountVowelsAndConsonants(inputString);

        Console.WriteLine("Vowels: " + counts[0]);
        Console.WriteLine("Consonants: " + counts[1]);
    }

    static int[] CountVowelsAndConsonants(string input)
    {
        int vowelCount = 0;
        int consonantCount = 0;

        foreach (char c in input)
        {
            switch (Char.ToLower(c))
            {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                    vowelCount++;
                    break;
                default:
                    consonantCount++;
                    break;
            }
        }

        int[] counts = { vowelCount, consonantCount };
        return counts;
    }
}
解释说明

在上述代码中,我们首先定义了一个CountVowelsAndConsonants函数,它接受一个字符串参数input。该函数使用foreach循环遍历字符串中的每个字符,并使用switch语句判断字符是否为元音或辅音。计数器vowelCountconsonantCount分别用于统计元音和辅音的数量。

Main函数中,我们定义了一个示例字符串inputString,并调用CountVowelsAndConsonants函数来计算元音和辅音的数量。然后将结果输出到控制台。

结论

通过本文,你学会了如何使用C#编写一个程序来计算给定字符串中元音和辅音的数量。你可以根据自己的需要进行扩展和修改,例如添加其他字符类型的统计。在实际应用中,你可以将该函数集成到你的C#项目中,用于处理字符串的统计需求。

希望本文对你有所帮助!