开发者

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

I have开发者_如何学Python a string that contains an int. How can I parse the int in C#?

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?


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.

To reduce the chance of an overflow you could instead use 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.


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:

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜