1. char * strcat()
#include <stdio.h>
char * strcat(char * s1,const char * s2) {
char *p=s1;
while (*p)
p++;
while(*p++ = *s2++)
;
return s1;
}
2.size_t strlen(const char *s) {
const char * p=s;
while(*s)
s++;
return s-p;
}
为何要编写strlen?
毕竟有sizeof运算符。
假设 char *str="hello";
理所当然的去尝试输出sizeof(str),发现输出的是4,原来sizeof(str)输出的是指针的大小
再次输出sizeof(*str),发现输出的是1,是sizeof(char)的值。
于是必须编写求字符串的大小的函数。
如果是 char str[]="hello",sizeof(str)输出的是6,正确输出字符串的内存大小
可以发现sizeof求的是内存大小。
3. char * strcmp( )
int strcmp (const char * s1,const char *s2) {
int i;
for(i=0;s1[i] == s2[i];++i)
if(s1[i]=='\0')
return 0;
return s1[i]-s2[i];
}
惯用法:
1.查找字符串末尾:
while (*p)
p++;
2.复制
while(*p++ = *s2++)
;