C# 计算元音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18109890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Count Vowels
提问by Phorden
I am learning to program C# and I am trying to count the vowels. I am getting the program to loop through the sentence, but instead of returning vowel count, it is just returning the length of the string. Any help would be greatly appreciated.
我正在学习编程 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();
}
采纳答案by Reed Copsey
Right now, you're checking whether the sentence as a whole contains
any vowels, once for each character. You need to instead check the individual characters.
现在,您正在检查整个句子是否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++;
}
}
That being said, you can simplify this quite a bit:
话虽如此,您可以将其简化很多:
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();
}
You can simplify it further if you want to use LINQ:
如果你想使用 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();
}
回答by CBredlow
That's because your if statement is always true, you need to compare the character at sentence[i], and see if it is a vowel, instead of seeing if the sentence contains a vowel.
那是因为您的 if 语句始终为真,您需要比较句子 [i] 处的字符,看看它是否是元音,而不是看句子是否包含元音。
回答by Tyler
Or with linq.
或者用 linq。
static void Main()
{
int total = 0;
Console.WriteLine("Enter a Sentence");
string sentence = Console.ReadLine().ToLower();
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
total = sentence.Count(x => vowels.Contains(x));
Console.WriteLine("Your total number of vowels is: {0}", total);
Console.ReadLine();
}
回答by Curt
int cnt = 0;
for (char c in sentence.ToLower())
if ("aeiou".Contains(c))
cnt++;
return cnt;
回答by Federico Berasategui
Maybe too advanced for a starter, but this is the way you do that in C#:
对于初学者来说可能太高级了,但这是您在 C# 中执行此操作的方式:
var vowels = new[] {'a','e','i','o','u'};
Console.WriteLine("Enter a Sentence");
var sentence = Console.ReadLine().ToLower();
var vowelcount = sentence.Count(x => vowels.Contains(x));
Console.WriteLine("Your total number of vowels is: {0}", vowelcount);
Console.ReadLine();
回答by Louis Ricci
You were checking to see if your whole sentence contained vowels for every iteration of your loop, which is why your total was simply the number of characters in your sentence string.
您正在检查您的整个句子是否包含循环的每次迭代的元音,这就是为什么您的总数只是句子字符串中的字符数。
foreach(char ch in sentence.ToLower())
if("aeiou".Contains(ch))
total++;
Better yet use a regular expression. editYou'd only want to use a regex for something a little more complex than matching vowels.
最好还是使用正则表达式。编辑您只想将正则表达式用于比匹配元音更复杂的事情。
using System.Text.RegularExpressions;
...
int total = Regex.Matches(sentence, @"[AEIOUaeiou]").Count;
EDITJust for completeness the fastest/most efficient (if you were to do this on a ~million strings) solution. If performance wasn't a concern I'd use Linq for its brevity.
编辑只是为了完整性最快/最有效(如果您要在大约百万个字符串上执行此操作)解决方案。如果性能不是问题,我会使用 Linq 以求简洁。
public static HashSet<char> SVowels = new HashSet<char>{'a', 'e', 'i', 'o', 'u'};
public static int VowelsFor(string s) {
int total = 0;
foreach(char c in s)
if(SVowels.Contains(c))
total++;
return total;
}
回答by Antarr Byrd
This is how I would handle this.
这就是我将如何处理这个。
var sentence = "Hello my good friend";
var sb = sentence.ToLower().ToCharArray();
var count = 0;
foreach (var character in sb)
{
if (character.Equals('a') || character.Equals('e') || character.Equals('i') || character.Equals('o') ||
character.Equals('u'))
{
count++;
}
}
回答by fatsmcgee
Since Reed has answered your question, I will offer you another way to implement this. You can eliminate your loop by using LINQ and lambda expressions:
由于 Reed 已经回答了您的问题,我将为您提供另一种实现方式。您可以使用 LINQ 和 lambda 表达式来消除循环:
string sentence = "The quick brown fox jumps over the lazy dog.";
int vowelCount = sentence.Count(c => "aeiou".Contains(Char.ToLower(c)));
If you don't understand this bit of code, I'd highly recommend looking up LINQ and Lambda Expressions in C#. There are many instances that you can make your code more concise by eliminating loops in this fashion.
如果您不理解这段代码,我强烈建议您在 C# 中查找 LINQ 和 Lambda 表达式。在许多情况下,您可以通过以这种方式消除循环来使代码更加简洁。
In essence, this code is saying "count every character in the sentence that is contained within the string "aeiou". "
本质上,这段代码是在说“计算包含在字符串“aeiou”中的句子中的每个字符。”
回答by xanatos
There are many ways to skin a cat :-) In programming a little lateral thinking can be useful...
有很多方法可以给猫剥皮 :-) 在编程中稍微横向思考会很有用......
total += sentence.Length - sentence.Replace("a", "").Length;
total += sentence.Length - sentence.Replace("e", "").Length;
total += sentence.Length - sentence.Replace("i", "").Length;
total += sentence.Length - sentence.Replace("o", "").Length;
total += sentence.Length - sentence.Replace("u", "").Length;
You could, for example, try removing a vowel from the sentence and looking if the sentence is smaller without the vowel, and by how much.
例如,您可以尝试从句子中删除一个元音,然后查看没有元音的句子是否更小,以及小了多少。
回答by Chris
You can also do this with switch statement
您也可以使用 switch 语句执行此操作
var total = 0;
var sentence = "Hello, I'm Chris";
foreach (char c in sentence.ToLower())
{
switch (c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
total++;
break;
default: continue;
}
}
Console.WriteLine(total.ToString());