Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

atoi

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.

like image 241
Jeremy Stein Avatar asked Nov 29 '22 06:11

Jeremy Stein


2 Answers

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);
like image 176
Timbo Avatar answered Jan 22 '23 12:01

Timbo


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;
like image 42
stevehipwell Avatar answered Jan 22 '23 12:01

stevehipwell