i want to count how many numbers from 0 to 9 is in string. tried some code but it don’t works, it returns 0 every time. whats wrong and how to fix? also if u can tell me how do it with srting.Count() method. thanks.
// 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
Use a simple regex for that?
Outputs
6. This picks up only the isolated digits, not the ones that are part of two or more digit numbers.EDIT: I somehow completely missed the question tag being ‘c#’ and wrote my original answer in python. Conveniently the actual regex pattern syntax required is the same in both python and c#.