Parse integer from string containing letters and s

2019-06-21 16:38发布

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.

6条回答
beautiful°
2楼-- · 2019-06-21 16:50

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');
  }
}
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-06-21 16:50

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));
查看更多
Bombasti
4楼-- · 2019-06-21 16:57

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));
查看更多
叛逆
5楼-- · 2019-06-21 17:04

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
}
查看更多
ゆ 、 Hurt°
6楼-- · 2019-06-21 17:10

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

string s = "RC 272";
int val = int.Parse(s.Split(' ')[1]); // val is 272
查看更多
做自己的国王
7楼-- · 2019-06-21 17:15

Since the format of the string will not change KISS:

string input = "RC 272";
int result = int.Parse(input.Substring(input.IndexOf(" ")));
查看更多
登录 后发表回答