samuraisxmali
samuraisxmali

Reputation: 103

count numbers (from 0 to 9) in string

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

Upvotes: 2

Views: 4844

Answers (9)

netsplit
netsplit

Reputation: 1130

I ran into this problem and LINQ wasn't available. However it was easy enough to port it the basic idea in the LINQ solution. Here's the nonLINQ solution:

int formatLength = 0;
foreach(char maybeDigit in format) {
           //use a ternary expression since C# can't cast bool to int
           formatLength += Char.IsDigit(maybeDigit) ? 1 : 0;
}

Upvotes: 0

Benedict
Benedict

Reputation: 2821

Use a simple regex for that?

  var matches = System.Text.RegularExpressions.Regex.Matches("1 2 3 4 5 6 10 11 12", "(?<![0-9])[0-9](?![0-9])");
  Console.WriteLine(matches.Count);

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#.

Upvotes: 4

Madan T
Madan T

Reputation: 1

string str = "429gfsj58347583jhfs094248324";

  for(j=0;j<=9;j++)
  {
     if (str.Contains(j.ToString()))
     {
       n++;
     }
   }

Response.Write(n.ToString());


Will return the numbers frequency
Answer: 20

If you want the count separatly please ask freely.

Regards,

Madan Tiwari

Upvotes: 0

shift66
shift66

Reputation: 11958

int n=0;
foreach (char a in str)
{
    if (a >= '0' && a <= '9')
          n++;
}

Just use this.
Explanation: Code of ASCII character 0 is 48 and character 9 is 57 (here you can find all character codes) and when you're comparing characters in C# it compares their's codes.
You could write if (a >= 48 && a <= 57)) and it would work as well. Hope it helped.
EDIT: I read your comment.

for(int = 1; i < str.length-1; i++)
{
    if(Char.IsDigit(str[i])) &&
       !Char.IsDigit(str[i-1]) &&
       !Char.IsDigit(str[i+1]))
        n++;
}

After this you should check first and last characters. That's all.

Upvotes: 4

Sebastian Siek
Sebastian Siek

Reputation: 2075

This should help you

public int CountDigits(string text)
{
    return text.Cast<int>().Count(c => c >= 48 && c <= 57);
}

Upvotes: 2

Henrik Gering
Henrik Gering

Reputation: 1871

An example of using string.count:

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

Upvotes: 5

paxdiablo
paxdiablo

Reputation: 881423

Bit hard to tell how your code is sequenced but, in the first block you set b to 0 and never change it.

That means that ((b > 0) && (b < 9)) will always be false.

I think you should probably be checking a rather than b.

You'll also strike the problem that the character '0' is not the same as the integer 0.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612964

With your current approach you would need to convert each character a from a character code into the corresponding integer. Use Int32.Parse(). In one of your attempts you used a (char)b cast but all this does is to give a character with the character code b.

It would be easier to write the test like this

foreach (char a in str)
    if ((a>='0') && (a<='9'))
        ....

Here I am using the syntax for a character literal, '0' as opposed to "0" which is a string literal.

Upvotes: 4

DNA
DNA

Reputation: 42597

In your first example, the condition if ((b > 0) && (b < 9)) is always false, because b starts out at zero and is never modified.

Upvotes: 1

Related Questions