天天看點

基礎函數的實作(strcpy,strcat, strcmp, atoi, itoa)

strcpy:

VERSION 1:

char *strcpy(char *strDestination, const char *strSource);

{

assert(strDestination && strSource);

char *cp=strDestination;

while(*cp++ = *strSource++);

return strDestination;

}

VERSION 2:

char* strcpy(char * dst, const char * src) 

char * cp = dst; 

while( *cp++ = *src++ ) 

;                            

return( dst ); 

}

VERSION 3:

char *srcpy(char *dest,const char *source)

{

assert((dest!=NULL)&&(source!=NULL));

char *address = dest;

while(*source!='/0')

{

*dest++=*source++;

}

*dest = '/0';

return address;

strcat:

VERSION 1:

char   *   strcat(char   *   dest,   const   char   *   src)  

{  

char   *tmp   =   dest;  

while   (*dest)  

dest++;  

while   ((*dest++   =   *src++)   !=   '/0')  

;  

return   tmp;  

}

strcmp:

VERSION 1:

int strcmp ( const char* src, const char* dst ) 

int ret = 0 ; 

while( !(ret = *(unsigned char *)src - *(unsigned char *)dst) && *dst) 

++src, ++dst; 

if ( ret < 0 ) 

ret = -1 ; 

else if ( ret > 0 ) 

ret = 1 ; 

return( ret ); 

VERSION 2:

int strcmp(const char *dest, const char *source)  

{  

assert((NULL != dest) && (NULL != source));  

while (*dest && *source && (*dest == *source))  

{  

dest ++;  

source ++;  

}  

return *dest - *source;  

}

VERSION 3:

int strcmp(char *source, char *dest)

{

assert(source != NULL && dest != NULL);

while(*source++==*dest++)

{

if(*source=='/0'&&*dest=='/0')

return 0;       

}

return -1;

}

itoa:

#include "stdafx.h"

#include <iostream>

using namespace std;

void itoa(int num,char str[] )

{

int sign = num,i = 0,j = 0;

char temp[11];

if(sign<0)//判斷是否是一個負數

{

num = -num;

};

do

{

temp[i] = num%10+'0';       

num/=10;

i++;

}while(num>0);

if(sign<0)

{

temp[i++] = '-';//對于負數,要加以負号

}

temp[i] = '/0';

i--;

while(i>=0)//反向操作

{

str[j] = temp[i];

j++;

i--;

}

str[j] = '/0';

}

atoi:

int atoi(char s[])

{

int i = 0,sum = 0,sign;    //輸入的數前面可能還有空格或制表符應加判斷

while(' '==s[i]||'/t'==s[i])

{

i++;

}

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

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

{

i++;

}

while(s[i]!='/0')

{

sum = s[i]-'0'+sum*10;

i++;

}   

return sign*sum;

}

繼續閱讀