您需要檢查元音和子音,但不要忘記檢查大寫和小寫。
要計算元音,請分別檢查「aeiou」字符,即
if (myStr[i] == 'a' || myStr[i] == 'e' || myStr[i] == 'i' || myStr[i] == 'o' || myStr[i] == 'u' || myStr[i] == 'A' || myStr[i] == 'E' || myStr[i] == 'I' || myStr[i] == 'O' || myStr[i] == 'U') { vowel_count++; }
以下是計算字串中元音數量的代碼。
現場示範
using System; public class Demo { public static void Main() { string myStr; int i, len, vowel_count, cons_count; myStr = "Avengers"; vowel_count = 0; cons_count = 0; // find length len = myStr.Length; for(i=0; i<len; i++) { if(myStr[i] =='a' || myStr[i]=='e' || myStr[i]=='i' || myStr[i]=='o' || myStr[i]=='u' || myStr[i]=='A' || myStr[i]=='E' || myStr[i]=='I' || myStr[i]=='O' || myStr[i]=='U') { vowel_count++; } else { cons_count++; } } Console.Write("Vowels in the string: {0}", vowel_count); } }
Vowels in the string: 3
以上是C# 程式計算字串中的元音的詳細內容。更多資訊請關注PHP中文網其他相關文章!