Monday, September 25, 2006

AtoI function - String to Integer in C# .NET

If you ever want to convert a string to integer, you have to go through the following checks


public static int StringToInt(string s)
{
int length = s.Length;
int i = 0;
int lastNumber = 0;
int returnNumber = 0;
bool numberNegative = false;
int startPoint = 0;

if (s[0] == '-')
{
numberNegative = true;
startPoint = 1;
}

for (i = startPoint; i < length; i++)
{
if (s[i] == ' ')
{
continue;
}
else
{
if ((s[i] >= '0') && s[i] <= '9')
{
returnNumber = s[i] - '0';
if (i > 0) lastNumber = lastNumber * 10;
lastNumber = lastNumber + returnNumber;
}
else
{
break;
}
}
}
if (numberNegative)
lastNumber = -1 * lastNumber;

return lastNumber;
}

4 comments:

Anonymous said...

have you ever heard of int.Parse()?

Raj Lal said...

Nice to see your message "Anonymous" The algorithm provided is meant to show the LOGIC behind int.Parse . How it can be implemented in any programming language.

Try to make your own implementation of int.parse , and then you will realize how challenging it can be

Gysb said...

A nice explanation of what is done behind Int.Parse.
Thanks a lot.

Anonymous said...

There are some bugs in this code.

Whitespace is not handled as intended for negative numbers:
"- 1"
will parse successfully, but
" -1"
will not

Also there is no checking for overflow, so parsing:
"21474836475"
yields 5
Wrapping those lines in checked{} would provide overflow checking.