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.
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
}
Since the format of the string will not change KISS:
string input = "RC 272";
int result = int.Parse(input.Substring(input.IndexOf(" ")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With