Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract number at end of string in C#

Probably over analysing this a little bit but how would stackoverflow suggest is the best way to return an integer that is contained at the end of a string.

Thus far I have considered using a simple loop, LINQ and regex but I'm curious what approaches I'll get from the community. Obviously this isn't a hard problem to solve but could have allot of variance in the solutions.

So to be more specific, how would you create a function to return an arbitrarily long integer/long that is appended at the end of an arbitrarily long string?

CPR123 => 123 ABCDEF123456 => 123456 
like image 525
Maxim Gershkovich Avatar asked Nov 01 '12 00:11

Maxim Gershkovich


People also ask

How do you extract the digits at the end of the string?

In C, you can use strpbrk. This gives the first occurance of any of a set of characters, so if it not guaranteed that the digits appear at the end of the string, you will need to call strpbrk until it returns null, saving the result of the previous call before the next call.

How do I extract an integer from the string in C?

How to extract numbers from string in C? Simple answer: Use strtol() or strtof() functions alongwith isdigit() function.

How do you read numbers in a string?

You can use sscanf here if you know the number of items you expect in the string: char const *s = "10 22 45 67 89"; sscanf(s, "%d %d %d %d %d", numbers, numbers+1, numbers+2, numbers+3 numbers+4);


2 Answers

Use this regular expression:

\d+$  var result = Regex.Match(input, @"\d+$").Value; 

or using Stack, probably more efficient:

var stack = new Stack<char>();  for (var i = input.Length - 1; i >= 0; i--) {     if (!char.IsNumber(input[i]))     {         break;     }      stack.Push(input[i]); }  var result = new string(stack.ToArray()); 
like image 162
Kirill Polishchuk Avatar answered Sep 22 '22 22:09

Kirill Polishchuk


Obligatory LINQ one-liner

var input = "ABCD1234"; var result = string.Concat(input.ToArray().Reverse().TakeWhile(char.IsNumber).Reverse()); 
like image 41
ttu Avatar answered Sep 21 '22 22:09

ttu