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.
This looks sooo beautiful:
string str = "26 things";
int x = int.Parse(str.TakeWhile(ch => char.IsDigit(ch)).Aggregate("", (s, ch) => s + ch));
And, the boring solution for anyone who really wants atoi:
[System.Runtime.InteropServices.DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int atoi(string str);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With