C# 计算元音、辅音和数字
我的代码怎么了?如果我输入aaa,它在元音行中返回3,但是如果我输入abc,它在元音行中也返回3 顺便说一下,这是windows窗体C# 计算元音、辅音和数字,c#,winforms,C#,Winforms,我的代码怎么了?如果我输入aaa,它在元音行中返回3,但是如果我输入abc,它在元音行中也返回3 顺便说一下,这是windows窗体 txtInputString.SelectionStart = 0; txtInputString.SelectionLength = txtInputString.Text.Length; txtInputString.Focus(); int vowelCount = 0, consonants = 0, nonNumeric = 0; int count
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();
试试看:
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();
通过预先加载所有辅音和元音,并应用一些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++;
}
您在每个循环中都会查看整个文本。您可以一步一步地调试应用程序,以了解您的错误。。。提示:您正在使用for循环,但没有在其中迭代任何CollectionTXInputString.Text.Contains'a'==true确定吗?最好检查txtInputString.Text.Contains'a'==true==true.:P-但说真的,您可能需要一个var-vouels=HashSet{'a',e',i',o',u'},然后检查vouels.ContainstxtInputString.Text[i]{vouelCount++;}。辅音也一样。还有,为什么最后一个计数器命名为非数字?如果输入是a1a,那么“1”将被计为非数字,这会很奇怪。而且您不需要txtVernel.Text=vouelCount.ToString+中的+;下一行。这个类有一些非常好的方法来确定是char还是。遗憾的是,没有元音。