Parse an integer from a string containing letters and spaces - C #

What is the most efficient way to parse an integer from a string containing letters and spaces?

Example: I passed the following line: "RC 272". I want to get 272 from a string.

I am using C # framework and .NET 2.0.

+4
source share
6 answers

Since the format of the string will not change KISS :

string input = "RC 272"; int result = int.Parse(input.Substring(input.IndexOf(" "))); 
+9
source

A simple regular expression can extract a number, and then you can parse it:

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

If a string can contain several numbers, you can simply iterate 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 } 
+17
source

If it will always be in the format "ABC 123":

 string s = "RC 272"; int val = int.Parse(s.Split(' ')[1]); // val is 272 
+2
source

Just for fun, another possibility:

 int value = 0; foreach (char c in yourString) { if ((c >= '0') && (c <= '9')) { value = value*10+(c-'0'); } } 
+1
source

EDIT:

If it always will be in this format, it does not look like the next job, where value = "RC 272"?

 int someValue = Convert.ToInt32(value.Substring(value.IndexOf(' ') + 1)); 
0
source

Guys, since it will always be in the "ABC 123" format, why not skip the IndexOf step?

 string input = "RC 272"; int result = int.Parse(input.Substring(3)); 
0
source

All Articles