开发者

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 ret开发者_Go百科rieve 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(" ")));


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');
  }
}


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

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


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));


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜