I am working on .NET project and I am trying to parse only the numeric value from string. For example,
string s = "12ACD";
int t = someparefun(s);
print(t) //t should be 12
A couple assumptions are
- The string pattern always will be number follow by characters.
- The number portion always will be either one or two digits value.
Is there any C# predefined function to parse the numeric value from string?
There’s no such function, at least none I know of. But one method would be to use a regular expression to remove everything that is not a number:
This function will yield
12for12ABC, so if you need to be able to process negative numbers, you’ll need a different solution. It is also not safe, if you pass it only non-digits it will yield aFormatException. Here is some example data:A little bit more verbose but safer approach would be to use
int.TryParse():Some example data again:
Or if you only want the first number in the string, basically stopping at meeting something that is not a digit, we suddenly also can treat negative numbers with ease:
And again we test it:
Overall, if we’re talking about user input I would consider not accepting invalid input at all, only using
int.TryParse()without some additional magic and on failure informing the user that the input was suboptimal (and maybe prompting again for a valid number).