Sunday, August 19, 2007

atoi() function in c# .net - convert string to integer

 

public static int atoi(string str)
{
int sign=1;
int TheNumber=0;
int tmp=0;
int x=0;
int l=(str.Length)-1;
char[] c=str.ToCharArray();

if ('-'==c[0]){sign=-1; x=1;}

for(;x < l;x++)
{
if ((c[x]>='0')&&(c[x]<='9'))
{
tmp=(c[x]-'0');//0 is the 0 index
TheNumber=TheNumber*10+tmp; //to enlarge the number by *10 every time
}
}

return TheNumber*sign;

}

Technorati Tags:

1 comment:

barrtender said...

This doesn't work right...

You're cutting off the last digit by setting l to length-1.

 
Dotster Domain Registration Special Offer