开发者

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

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.


Using LINQ :

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

or

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


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.


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));


    string str = "t12X234";
    var reversed = str.Reverse().ToArray();
    int digits = 0;

    while (digits < str.Length &&
           Char.IsDigit(reversed[digits])) digits++;

    int num = Convert.ToInt32(str.Substring(str.Length - digits));

This gives num 234 as output if that is what you need.

The other linq/lambda variants just count characters which I think is not completely correct if you have a string like "B2B_MESSAGE_12344", because it would count the 2 in B2B.

But I'm not sure if I understood correctly what number of numbers means. Is it the count of numbers (other answers) or the number that numbers form (this answer).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜