4

I have 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?

1
  • 1
    What would you want to happen for input of 15per13so14n, for example? Commented Jun 21, 2011 at 11:41

4 Answers 4

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

Use something like this :

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

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

Comments

1

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.

3 Comments

You can use input.Where(Char.IsDigit) to get the digits.
@Guffa Thanks, I've edited the answer accordingly. This actually came from an extension method I'm using frequently that checks any string for valid/invalid characters, and I just refactored the "valid chars" parameter into "0123456789".
You don't need to make the lambda expression c => Char.IsDigit(c), you can use just Char.IsDigit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.