我正在尝试用 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/