2013-07-05 15:47:19
本函数给出了几种strcat与strncat的实现,有ugly implementation,也有good implementation。并参考标准库中的implementation,最后给出了比较好的implementation。
注意以下几点:
对于while (*cp++),要注意循环结束时,指针指向的位置是否是预期的,如下面的:
while ( *cp )
cp++;
与
while (*cp++)
;
cp--;
的效果是一样的。
在第二种写法中就要注意在结束循环后,对cp减1,才能指向字符串结束符的位置。
while (*cp++ != ' ');可以用while ( *cp++ );代替
同样while ( (*cp++ = *src++) != ' ');可用while ( *cp++ = *src++ );代替
_strncat_1可实现与标准库函数即_strncat_2同样的功能,可以使得在count大于、小于以及等于source长度时,加上字符串结束符,且加入了输入合法性检查;但_strncat_1的写法更为简洁
小结:
标准库函数并没有输入合法性检查,这将输入合法性检查的任务推给了函数的调用者。
对于strcat函数,好的implementation要考虑一下几点:
- 函数src参数应为const,dst参数为非const,count为size_t类型;
- 函数要返回dst的地址,以方便嵌套使用该函数;
- 确定dst要有字符串结束符;
- 注意输入合法性检查注意输入合法性检查。
对于strncpy函数,除了以上几点外,好的implementation还要考虑:
当source的长度小于count时,应该怎么办?
标准库函数的做法是,将source的所有有效字符复制完成后,再加一个字符串结束符;当source的长度大于火等于count时,将source的count个有效字符复制完成后,再加一个字符串结束符
代码:
1 #include <iostream> 2 3 using namespace std; 4 #define SIZE 100 5 6 /*** 7 *char *strcat(dst, src) - concatenate (append) one string to another 8 * 9 *Purpose: 10 * Concatenates src onto the end of dest. Assumes enough 11 * space in dest. 12 * 13 *Entry: 14 * char *dst - string to which "src" is to be appended 15 * const char *src - string to be appended to the end of "dst" 16 * 17 *Exit: 18 * The address of "dst" 19 * 20 *Exceptions: 21 * 22 *******************************************************************************/ 23 24 //代码写的比较笨拙 25 //while (*cp++ != ' ');可以用while ( *cp++ );代替 26 //同样while ( (*cp++ = *src++) != ' ');可用while ( *cp++ = *src++ );代替 27 char * _strcat_1(char *dst,char *src) 28 { 29 if (NULL == dst || NULL == src) 30 { 31 return dst; 32 } 33 char *cp = dst; 34 while (*cp++ != '