C函数的实现(strcpy,atoi,atof,itoa,reverse)

在笔试面试中经常会遇到让你实现C语言中的一些函数比如strcpy,atoi等

1. atoi

把字符串s转换成数字

 

int Atoi( char *s )

{

	int num = 0, i = 0;

	int sign = 1;

	

	for( i=0; isspace(s[i]); i++ );

	

	sign = (s[i] == '-')? -1:1;

	

	if( s[i] == '+' || s[i] == '-' )

		i++;

	

	for( ;isdigit(s[i]); i++ )

	{

		num = 10*num + (s[i]-'0');

	}

	

	return sign*num;

}



2. strcpy(char *src, char *dst)

 

把src复制到dst中

 

int Strcpy(char* src, char *dst)

{

//	register char *tmp;

	int i = 0;

	while( src[i]!= NULL )

	{

		dst[i] = src[i++];

	}

}

 

 

3.itoa( int n, char *s )

把数字转化成字符串

 

void Reverse( char *s )

{

	int size = 0;

	char tmp;

	

	while( s[size] != NULL )

		size++;

	size--;

	

	int i=0;

	while( i <= size>>1 )

	{

		tmp = s[i], s[i] = s[size-i], s[size-i] = tmp;

		i++;

	}

}



void ItoA( int n, char *s )

{

	int sign = 1;

	

	if( n < 0 )

	{

		sign = -1;		

		n = -n;

	}

	

	int i=0; 

	do

	{

		s[i++] = n%10 + '0';

	}	while((n/=10) > 0);

	

	if( sign == -1 )

		s[i++] = '-';

	s[i] = '\0';

	Reverse( s );

}


4. atof( char * s )

 

把字符串转化成double类型

 

double AtoF( char *s )

{

	int sign = 1;

	int i = 0;

	for( i=0; isspace(s[i]); i++ );

	

	sign = (s[i] == '-')? -1:1;

	

	if( s[i] == '+' || s[i] == '-' )

		i++;

		

	double num = 0.0;

	double pow = 1.0;

	//整数 

	for( ;isdigit(s[i]); i++ )

		num = num*10 + (s[i]-'0');

		

	for( i++; isdigit(s[i]); i++ )

	{

		num = num*10 + (s[i]-'0');

		pow *= 10;

	}

	

	return sign * (num/pow);

}


 


 

你可能感兴趣的:(RCP)