我想计算从0到9的数字是多少个字符串.尝试了一些代码,但它不起作用,每次都返回0.什么是错的,如何解决?如果你能告诉我如何使用srting.Count()方法.谢谢.
// Attempt 1
string str = textBox1.Text;
int b = 0;
int n = 0;
foreach (char a in str)
{
if ((b > 0) && (b < 9))
{
if ((char)b == a)
n++;
}
}
label1.Text = n;
// Attempt 2
string str = textBox1.Text;
int n = 0;
foreach (char a in str)
{
int[] k = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
foreach (int b in k)
{
if (b == a)
n += 1;
}
}
label1.Text = n
Run Code Online (Sandbox Code Playgroud)
使用string.count的一个例子:
int result = "1 2 2 5 2 4".Count(char.IsDigit);