C#计数元音

我正在学习编程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(); } 

现在,您正在检查整个句子是否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++; } } 

话虽这么说,你可以简化这一点:

 static void Main() { int total = 0; // Build a list of vowels up front: var vowels = new HashSet { '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(); } 

如果要使用LINQ,可以进一步简化:

 static void Main() { // Build a list of vowels up front: var vowels = new HashSet { '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(); } 

这是因为你的if语句总是正确的,你需要比较句子[i]中的字符,看看它是否是元音,而不是看句子是否包含元音。

由于里德回答了你的问题,我将为你提供另一种实现方法。 您可以使用LINQ和lambda表达式消除循环:

 string sentence = "The quick brown fox jumps over the lazy dog."; int vowelCount = sentence.Count(c => "aeiou".Contains(Char.ToLower(c))); 

如果您不理解这段代码,我强烈建议您在C#中查找LINQ和Lambda表达式。 有许多实例可以通过以这种方式消除循环来使代码更简洁。

从本质上讲,这段代码是说“计算句子中包含的所有字符”aeiou“。”

您正在检查您的整个句子是否包含循环的每次迭代的元音,这就是为什么您的总数只是句子字符串中的字符数。

 foreach(char ch in sentence.ToLower()) if("aeiou".Contains(ch)) total++; 

更好的是使用正则表达式。 编辑你只想使用正则表达式比匹配元音更复杂的东西。

 using System.Text.RegularExpressions; ... int total = Regex.Matches(sentence, @"[AEIOUaeiou]").Count; 

编辑只是为了完整性,最快/最有效(如果你在一百万字符串上做这个)解决方案。 如果性能不是一个问题,我会使用Linq简洁。

 public static HashSet SVowels = new HashSet{'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; } 

或者用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(); } 

皮肤猫的方法有很多种:-)在编程中,一点横向思维可能很有用……

 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; 

例如,您可以尝试从句子中删除元音,并查看句子是否较小而没有元音,以及多少。

 int cnt = 0; for (char c in sentence.ToLower()) if ("aeiou".Contains(c)) cnt++; return cnt; 

对于初学者来说可能太高级了,但这是你在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(); 

这就是我如何处理这个问题。

 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++; } } 

您也可以使用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()); 

TMTOWTDI(Tim Toadie正如他们所说:有多种方法可以做到这一点)。

怎么样

 static char[] vowels = "AEIOUaeiou".ToCharArray() ; public int VowelsInString( string s ) { int n = 0 ; for ( int i = 0 ; (i=s.IndexOfAny(vowels,i)) >= 0 ; ) { ++n ; } return n; } 

或(另一种正则表达方式)

 static readonly Regex rxVowels = new Regex( @"[^AEIOU]+" , RegexOptions.IgnoreCase ) ; public int VowelCount( string s ) { int n = rxVowels.Replace(s,"").Length ; return n ; } 

最简单的可能也是最快的:

 public int VowelCount( string s ) { int n = 0 ; for ( int i = 0 ; i < s.Length ; +i ) { switch( s[i] ) { case 'A' : case 'a' : case 'E' : case 'e' : case 'I' : case 'i' : case 'O' : case 'o' : case 'U' : case 'u' : ++n ; break ; } } return n ; } 

这是计算元音的一种很好的通用方法,从这里你可以做各种各样的事情。 计算元音,返回排序列表等。

 public static int VowelCount(String vowelName) { int counter = 0; char[] vowels = { 'a', 'e', 'i', 'o', 'u' }; for (int index = 0; index < vowelName.Length; index++) { if (vowels.Contains(vowelName[index])) { counter++; } } return counter; } 
  static void Main(string[] args) { Char[] ch; Console.WriteLine("Create a sentence"); String letters = Console.ReadLine().Replace(" ", "").ToUpper(); ch = letters.ToCharArray(); int vowelCounter = 0; int consonantCounter = 0; for(int x = 0; x < letters.Length; x++) { if(ch[x].ToString().Equals("A") || ch[x].ToString().Equals("E") || ch[x].ToString().Equals("I") || ch[x].ToString().Equals("O") || ch[x].ToString().Equals("U")) { vowelCounter++; } else { consonantCounter ++; } } System.Console.WriteLine("Vowels counted : " + vowelCounter); System.Console.WriteLine("Consonants counted : " + consonantCounter); 

申请计算句子中的元音和辅音字母。 这是另一种解决方案,使用较少的代码行来理解使用循环和嵌套循环与char数组的想法。

具有控件名称的应用程序界面:

带控件名称的应用程序界面

 namespace Program8_4 { public partial class Form1 : Form { // declare the counter variables in field int iNumberOfVowels = 0; int iNumberOfConsonants = 0; public Form1() { InitializeComponent(); } private void btnFind_Click(object sender, EventArgs e) { // call the methods in this event GetVowels(txtStringInput.Text); GetConsonants(txtStringInput.Text); // show the result in a label lblOutput.Text = "The number of vowels : " + iNumberOfVowels.ToString()+ Environment.NewLine+ "The number of consonants : " + iNumberOfConsonants.ToString(); // assign zero the counters to not add the previous number to new number, and start counting from zero again iNumberOfVowels = 0; iNumberOfConsonants = 0; } private int GetConsonants(string strFindConsonants) { // Declare char array to contain consonants letters char[] chrConsonants = { 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'X', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'x' }; // loop to get each letter from sentence foreach (char Consonants in strFindConsonants) { // another nested loop to compare each letter with all letters contains in chrConsonants array for (int index= 0; index 
 void main() { int x=0; char ch; printf("enter a statement:"); while((ch=getche())='\r') { if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') x++; } printf("total vowels="); getch(); }