基礎函數的實現(strcpy,strcat, strcmp, atoi, itoa)【轉】

 
strcpy:
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++ )
;                            /* Copy src over dst */
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;  
/*如果dest > source,則返回值大於0,如果dest = source,則返回值等於0,如果dest < source ,則返回值小於0。*/
}

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;
}
發佈了15 篇原創文章 · 獲贊 15 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章