您的位置:首页 > 其它

基础函数的实现(strcpy,strcat, strcmp, atoi, itoa)

2012-01-29 11:18 429 查看
基础函数的实现(strcpy,strcat, strcmp, atoi, itoa)

strcpy:

/**********************

* C语言标准库函数strcpy的一种典型的工业级的最简实现

* 返回值:

* 返回目标串的地址。

* 对于出现异常的情况ANSI-C99标准并未定义,故由实现者决定返回值,通常为NULL。

* 参数:

* strDeatination

*  目标串

* strSource

* 源串

***********************/

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++ )

; /* 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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: