Parse integer from string containing letters and spaces - C#

99封情书 提交于 2019-12-10 14:49:24

问题


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.


回答1:


Since the format of the string will not change KISS:

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



回答2:


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
}



回答3:


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



回答4:


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

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



回答5:


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



回答6:


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


来源:https://stackoverflow.com/questions/1596251/parse-integer-from-string-containing-letters-and-spaces-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!