Search code examples
.netatoi

Is there a .NET equivalent to C's atoi function?


If I have a string like:

"26 things"

I want to convert it to 26. I just want the integer at the beginning of the string.

If I was using C, I'd just use the atoi function. But I can't seem to find anything equivalent in .NET.

What's the easiest way to grab the integer from the beginning of a string?

Edit: I'm sorry I was ambiguous. The answers that look for a space character in the string will work in many circumstances (perhaps even mine). I was hoping for an atoi-equivalent in .NET. The answer should also work with a string like "26things". Thanks.


Solution

  • This should work (edited to ignore white-space at the begining of the string)

    int i = int.Parse(Regex.Match("26 things", @"^\s*(\d+)").Groups[1].Value);
    

    If you are worried about checking if there is a value you could do the following to give you a -1 value if there is no integer at the begining of the string.

    Match oMatch = Regex.Match("26 things", @"^\s*(\d+)");
    int i = oMatch.Success ? int.Parse(oMatch.Groups[1].Value) : -1;