在笔试面试中经常会遇到让你实现C语言中的一些函数比如strcpy,atoi等
1. atoi
把字符串s转换成数字
1 int Atoi( char *s ) 2 { 3 int num = 0, i = 0; 4 int sign = 1; 5 6 for( i=0; isspace(s[i]); i++ ); 7 8 sign = (s[i] == '-')? -1:1; 9 10 if( s[i] == '+' || s[i] == '-' ) 11 i++; 12 13 for( ;isdigit(s[i]); i++ ) 14 { 15 num = 10*num + (s[i]-'0'); 16 } 17 18 return sign*num; 19 }
2. strcpy(char *src, char *dst)
把src复制到dst中
1 int Strcpy(char* src, char *dst) 2 { 3 // register char *tmp; 4 int i = 0; 5 while( src[i]!= NULL ) 6 { 7 dst[i] = src[i++]; 8 } 9 }
3.itoa( int n, char *s )
把数字转化成字符串
1 void Reverse( char *s ) 2 { 3 int size = 0; 4 char tmp; 5 6 while( s[size] != NULL ) 7 size++; 8 size--; 9 10 int i=0; 11 while( i <= size>>1 ) 12 { 13 tmp = s[i], s[i] = s[size-i], s[size-i] = tmp; 14 i++; 15 } 16 } 17 18 void ItoA( int n, char *s ) 19 { 20 int sign = 1; 21 22 if( n < 0 ) 23 { 24 sign = -1; 25 n = -n; 26 } 27 28 int i=0; 29 do 30 { 31 s[i++] = n%10 + '0'; 32 } while((n/=10) > 0); 33 34 if( sign == -1 ) 35 s[i++] = '-'; 36 s[i] = ''; 37 Reverse( s ); 38 }
4. atof( char * s )
把字符串转化成double类型
1 double AtoF( char *s ) 2 { 3 int sign = 1; 4 int i = 0; 5 for( i=0; isspace(s[i]); i++ ); 6 7 sign = (s[i] == '-')? -1:1; 8 9 if( s[i] == '+' || s[i] == '-' ) 10 i++; 11 12 double num = 0.0; 13 double pow = 1.0; 14 //整数 15 for( ;isdigit(s[i]); i++ ) 16 num = num*10 + (s[i]-'0'); 17 18 for( i++; isdigit(s[i]); i++ ) 19 { 20 num = num*10 + (s[i]-'0'); 21 pow *= 10; 22 } 23 24 return sign * (num/pow); 25 }
转自http://blog.csdn.net/matrix_laboratory/article/details/12028431