How can I count the numbers in a string of mixed text/numbers

26,140

Solution 1

Using LINQ :

var count = jobId.Count(x => Char.IsDigit(x));

or

var count = jobId.Count(Char.IsDigit);

Solution 2

int x = "xxx123432".Count(c => Char.IsNumber(c)); // 6

or

int x = "xxx123432".Count(c => Char.IsDigit(c)); // 6

The difference between these two methods see at Char.IsDigit and Char.IsNumber.

Solution 3

Something like this maybe?

string jobId = "xxx123432";
int digitsCount = 0;
foreach(char c in jobId)
{
  if(Char.IsDigit(c))
    digitsCount++;
}

And you could use LINQ, like this:

string jobId = "xxx123432";
int digitsCount = jobId.Count(c => char.IsDigit(c));
Share:
26,140
OneFreeFitz
Author by

OneFreeFitz

I'm a software and web developer at Total Solutions, Inc. in Brighton, MI. Our focus is document capture, business automation, and everything SharePoint. We partner with, leverage, and customize a number of 3rd party SharePoint tools including NewsGator Social Sites, K2, Nintex, Quest, and Idera.

Updated on July 09, 2022

Comments

  • OneFreeFitz
    OneFreeFitz almost 2 years

    So what I'm trying to do, is take a job number, which looks like this xxx123432, and count the digits in the entry, but not the letters. I want to then assign the number of numbers to a variable, and use that variable to provide a check against the job numbers to determine if they are in a valid format.

    I've already figured out how to perform the check, but I have no clue how to go about counting the numbers in the job number.

    Thanks so much for your help.