c# - 为什么我的程序不读取索引 0 之后的后续字母?

标签 c#

我正在尝试用 C# 编写代码并遇到了这个问题,它说我需要计算输入的字符串中有多少个元音字母。它只标识第一个字母。这是程序:

class CountVowelsModularized
{
    public static void Main()
    {
        // Write your main here.
        string word;

        WriteLine("Enter a word");
        word=ReadLine().ToUpper();

        WriteLine("This word has {0} vowels", CountVowels(word));
    }

    public static int CountVowels(string phrase)
    {
        // Write your CounVowels method here.
        int vowel_count=0;
        int i=0;
        for(i=0;i<phrase.Length;i++)
        {
            if(phrase[i]=='A'||phrase[i]=='E'||phrase[i]=='I'||phrase[i]=='O'||phrase[i]=='U')
            {
                vowel_count++;
                ++;
            }
            else
                i++;
        }

        return vowel_count;
    }
}

最佳答案

如果您删除我注释掉的行,您的代码就可以正常工作:

public static int CountVowels(string phrase)
{
    // Write your CounVowels method here.
    int vowel_count = 0;
    int i = 0;
    for (i = 0; i < phrase.Length; i++)
    {
        if (phrase[i] == 'A' || phrase[i] == 'E' || phrase[i] == 'I' || phrase[i] == 'O' || phrase[i] == 'U')
        {
            vowel_count++;
            // ++; - DELETE THIS
        }
        // else - DELETE THIS
            // i++; - DELETE THIS
    }

    return vowel_count;
}

如果你想让你的代码更简洁一点,这里是一个简单的重构:

public static int CountVowels(string phrase)
{
    // Write your CounVowels method here.
    int vowel_count = 0;
    for (int i = 0; i < phrase.Length; i++)
    {
        if ("AEIOU".Contains(phrase[i]))
        {
            vowel_count++;
        }
    }
    return vowel_count;
}

如果您想进行更彻底的重构,请尝试以下操作:

public static int CountVowels(string phrase) => phrase.Where(p => "AEIOU".Contains(p)).Count();

关于c# - 为什么我的程序不读取索引 0 之后的后续字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62380735/

相关文章:

c# - MvvmLight RaisePropertyChanged ("")

c# - 如何让 .NET Core 项目将 NuGet 引用复制到构建输出?

c# - 在 ASP .NET MVC 应用程序中创建用户角色时出现错误

c# - 使用游标从使用 C# 的 SQL Server 读取时间序列数据?

C# autostart 自动将应用程序添加到启动文件夹

c# - Visual Studio 在线错误解析解决方案文件位于 *.xproj

c# - 比较两个列表以搜索常见项目

c# - 防止窗口跨越多个显示器

c# - 控件的事件到外部静态类方法

c# - 为什么在 DataGridTextcolumn 中找不到 ObservableCollection 中实际类的属性,但父类属性是?