从包含字母和空格的字符串中解析整数 - C#

Mic*_*ern 5 .net parsing c#-2.0

从包含字母和空格的字符串中解析整数的最有效方法是什么?

示例:我传递了以下字符串:"RC 272".我想从字符串中检索272.

我正在使用C#和.NET 2.0框架.

Luc*_*ero 20

一个简单的正则表达式可以提取数字,然后你可以解析它:

int.Parse(Regex.Match(yourString, @"\d+").Value, NumberFormatInfo.InvariantInfo);
Run Code Online (Sandbox Code Playgroud)

如果字符串可能包含多个数字,您可以循环使用相同的正则表达式找到的匹配项:

for (Match match = Regex.Match(yourString, @"\d+"); match.Success; match = match.NextMatch()) {
    x = int.Parse(match.Value, NumberFormatInfo.InvariantInfo); // do something with it
}
Run Code Online (Sandbox Code Playgroud)


Gav*_*ler 9

由于字符串的格式不会改变KISS:

string input = "RC 272";
int result = int.Parse(input.Substring(input.IndexOf(" ")));
Run Code Online (Sandbox Code Playgroud)


Luc*_*ero 5

只是为了好玩,另一种可能性:

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