Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse integer from string containing letters and spaces - C#

What is the most efficient way to parse an integer out of a string that contains letters and spaces?

Example: I am passed the following string: "RC 272". I want to retrieve 272 from the string.

I am using C# and .NET 2.0 framework.

like image 844
Michael Kniskern Avatar asked Oct 20 '09 17:10

Michael Kniskern


2 Answers

A simple regex can extract the number, and then you can parse it:

int.Parse(Regex.Match(yourString, @"\d+").Value, NumberFormatInfo.InvariantInfo);

If the string may contain multiple numbers, you could just loop over the matches found using the same Regex:

for (Match match = Regex.Match(yourString, @"\d+"); match.Success; match = match.NextMatch()) {
    x = int.Parse(match.Value, NumberFormatInfo.InvariantInfo); // do something with it
}
like image 160
Lucero Avatar answered Oct 07 '22 21:10

Lucero


Since the format of the string will not change KISS:

string input = "RC 272";
int result = int.Parse(input.Substring(input.IndexOf(" ")));
like image 33
Gavin Miller Avatar answered Oct 07 '22 20:10

Gavin Miller