简体   繁体   English

如何从C#中的String解析int?

[英]How can I parse the int from a String in C#?

I have a string that contains an int. 我有一个包含int的字符串。 How can I parse the int in C#? 如何在C#中解析int?

Suppose I have the following strings, which contains an integer: 假设我有以下字符串,其中包含一个整数:

    15 person 
    person 15
    person15
    15person

How can I track them, or return null if no integer is found in the string? 如何跟踪它们,如果字符串中没有找到整数,则返回null

You can remove all non-digits, and parse the string if there is anything left: 您可以删除所有非数字,并在有任何内容时解析字符串:

str = Regex.Replace(str, "\D+", String.Empty);
if (str.Length > 0) {
  int value = Int32.Parse(str);
  // here you can use the value
}

Paste this code into a test: 将此代码粘贴到测试中:

public int? ParseAnInt(string s)
{
  var match = System.Text.RegularExpressions.Regex.Match(s, @"\d+");

  if (match.Success)
  {
    int result;
    //still use TryParse to handle integer overflow
    if (int.TryParse(match.Value, out result))
      return result;
  }
  return null;
}

[TestMethod]
public void TestThis()
{
  Assert.AreEqual(15, ParseAnInt("15 person"));
  Assert.AreEqual(15, ParseAnInt("person 15"));
  Assert.AreEqual(15, ParseAnInt("person15"));
  Assert.AreEqual(15, ParseAnInt("15person"));

  Assert.IsNull(ParseAnInt("nonumber"));
}

The method returns null is no number is found - it also handles the case where the number causes an integer overflow. 该方法返回null是没有找到数字 - 它还处理数字导致整数溢出的情况。

To reduce the chance of an overflow you could instead use long.TryParse 为了减少溢出的可能性,您可以使用long.TryParse

Equally if you anticipate multiple groups of digits, and you want to parse each group as a discreet number you could use Regex.Matches - which will return an enumerable of all the matches in the input string. 同样,如果您预期多个数字组,并且您希望将每个组解析为谨慎的数字,则可以使用Regex.Matches - 这将返回输入字符串中所有匹配项的可枚举数。

Use something like this : 使用这样的东西:

Regex r = new Regex("\d+");
Match m = r.Match(yourinputstring);

if(m.Success)
{
     Dosomethingwiththevalue(m.Value);
}

Since everyone uses Regex to extract the numbers, here's a Linq way to do it: 由于每个人都使用正则表达式来提取数字,所以这是Linq的方法:

string input = "15person";
string numerics = new string(input.Where(Char.IsDigit).ToArray());
int result = int.Parse(numerics);

Just for the sake of completeness, it's probably not overly elegant. 仅仅为了完整起见,它可能不会过于优雅。 Regarding Jaymz' comment, this would return 151314 when 15per13so14n is passed. 关于Jaymz的评论,当15per13so14n通过时,这将返回151314

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM