Pho*_*den 8 c# loops console-application
我正在学习编程C#而我正在尝试计算元音.我正在让程序遍历句子,但不是返回元音计数,而是返回字符串的长度.任何帮助将不胜感激.
static void Main()
{
int total = 0;
Console.WriteLine("Enter a Sentence");
string sentence = Console.ReadLine().ToLower();
for (int i = 0; i < sentence.Length; i++)
{
if (sentence.Contains("a") || sentence.Contains("e") || sentence.Contains("i") || sentence.Contains("o") || sentence.Contains("u"))
{
total++;
}
}
Console.WriteLine("Your total number of vowels is: {0}", total);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
Ree*_*sey 28
现在,你要检查整个句子是否有contains任何元音,每个字符一次.您需要检查单个字符.
for (int i = 0; i < sentence.Length; i++)
{
if (sentence[i] == 'a' || sentence[i] == 'e' || sentence[i] == 'i' || sentence[i] == 'o' || sentence[i] == 'u')
{
total++;
}
}
Run Code Online (Sandbox Code Playgroud)
话虽这么说,你可以简化这一点:
static void Main()
{
int total = 0;
// Build a list of vowels up front:
var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
Console.WriteLine("Enter a Sentence");
string sentence = Console.ReadLine().ToLower();
for (int i = 0; i < sentence.Length; i++)
{
if (vowels.Contains(sentence[i]))
{
total++;
}
}
Console.WriteLine("Your total number of vowels is: {0}", total);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
如果要使用LINQ,可以进一步简化:
static void Main()
{
// Build a list of vowels up front:
var vowels = new HashSet<char> { 'a', 'e', 'i', 'o', 'u' };
Console.WriteLine("Enter a Sentence");
string sentence = Console.ReadLine().ToLower();
int total = sentence.Count(c => vowels.Contains(c));
Console.WriteLine("Your total number of vowels is: {0}", total);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
由于 Reed 已经回答了您的问题,我将为您提供另一种实现方式。您可以使用 LINQ 和 lambda 表达式来消除循环:
string sentence = "The quick brown fox jumps over the lazy dog.";
int vowelCount = sentence.Count(c => "aeiou".Contains(Char.ToLower(c)));
Run Code Online (Sandbox Code Playgroud)
如果您不理解这段代码,我强烈建议您在 C# 中查找 LINQ 和 Lambda 表达式。在许多情况下,您可以通过以这种方式消除循环来使代码更加简洁。
本质上,这段代码是在说“计算包含在字符串“aeiou”中的句子中的每个字符。”