zoukankan      html  css  js  c++  java
  • 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] = '';
    	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);
    }



  • 相关阅读:
    最简单跳转,待反混爻的合集
    搜索引擎劫持代码
    Warning: Cannot modify header information
    editplus 正则删换行
    在全程Linux環境部署IBM Lotus Domino/Notes 8.5
    3.5-杂项②
    3.4-杂项①
    3.3-ISDN
    3.2-帧中继②
    3.2-帧中继①
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3341662.html
Copyright © 2011-2022 走看看