计算字符串中的数字(从0到9)

sam*_*ali 2 c# count

我想计算从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)

Hen*_*ing 6

使用string.count的一个例子:

int result = "1 2 2 5 2 4".Count(char.IsDigit);

  • 由于这是一个家庭作业问题,我认为该解决方案值得更多解释.这里,Count()方法将字符串作为单个字符的IEnumerable <Char>序列.'Char.IsDigit'方法是一个谓词,它有效地过滤掉任何不是数字的字符,剩下的是数字字符的计数.值得注意的是我们在这里使用LINQ和Char类型,而不是直接使用System.String. (3认同)