计算元音,辅音和数字

时间:2014-10-13 13:15:17

标签: c# winforms

我的代码出了什么问题?如果我输入aaa,它会在元音行中返回3,但如果我输入abc,它也会在元音行中返回3

顺便说一下,它是一个窗体。

txtInputString.SelectionStart = 0;
txtInputString.SelectionLength = txtInputString.Text.Length;
txtInputString.Focus();

int vowelCount = 0, consonants = 0, nonNumeric = 0; 
int count = txtInputString.TextLength;

for (int i = 0; i < count; i++)
{
    if ((txtInputString.Text.Contains('a') == true) || (txtInputString.Text.Contains('e') == true) || (txtInputString.Text.Contains('i')== true) || (txtInputString.Text.Contains('o')==true) || (txtInputString.Text.Contains('u')==true))
    {
        vowelCount++;
    }
    else if ((txtInputString.Text.Contains('b') == true) || txtInputString.Text.Contains('c') || txtInputString.Text.Contains("d") || txtInputString.Text.Contains("f") || txtInputString.Text.Contains("g"))
    {
        consonants++;
    }
    else
    {
        nonNumeric++;
    }
}
txtVowel.Text = vowelCount.ToString() + "";
txtConsonant.Text = consonants.ToString() + "";

txtNonNumeric.Text = nonNumeric.ToString();

2 个答案:

答案 0 :(得分:0)

试试:

    txtInputString.SelectionStart = 0;
    txtInputString.SelectionLength = txtInputString.TextLength;
    txtInputString.Focus();
    int vowelCount = 0, consonants = 0, nonNumeric = 0; 
    int count = txtInputString.TextLength;

    for (int i = 0; i < count; i++)
    {
        char c = txtInputString.Text.ElementAt(i);

        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
            vowelCount++;
        else if (c == 'b' || c =='c' || c == 'd' || c == 'f')
            consonants++;
        else
            nonNumeric++;
    }
    txtVowel.Text = vowelCount.ToString() + "";
    txtConsonant.Text = consonants.ToString() + "";

    txtNonNumeric.Text = nonNumeric.ToString();

答案 1 :(得分:0)

通过预先加载所有辅音和元音并应用一些LINQ,你可以使这更简单:

string consonants = "bcdfghjklmnpqrstvwxyz";
string vowels = "aeiou";
int vowelCount = 0, consonantCount = 0, nonNumericCount = 0;

var input = "alsdkghanivhusrvndb";  //some input         

foreach (char t in input)
{
   if (consonants.Any(c => c == t))
       consonantCount++;
   else if (vowels.Any(c => c == t))
       vowelCount++;
   else
       nonNumericCount++;
}