Michael Kniskern
Michael Kniskern

Reputation: 25260

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.

Upvotes: 6

Views: 20429

Answers (6)

GP.
GP.

Reputation: 1293

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

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

Upvotes: 0

Lucero
Lucero

Reputation: 60190

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
}

Upvotes: 29

Lucero
Lucero

Reputation: 60190

Just for the fun of it, another possibility:

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

Upvotes: 5

Wil P
Wil P

Reputation: 3371

EDIT:

If it will always be in that format wouldn't something like the following work where value = "RC 272"?

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

Upvotes: 0

John Rasch
John Rasch

Reputation: 63435

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

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

Upvotes: 2

Gavin Miller
Gavin Miller

Reputation: 43815

Since the format of the string will not change KISS:

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

Upvotes: 9

Related Questions