使用指针实现strcmp和strcat函数的功能
strcat:
#include <stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
char s[20]="hello";
char a[10]="horld";
char *p=s;
char *q=a;
#if 0
//strcpy
while(*q){
*p++=*q++
}
#endif
#if 1
//strcat
while(*p){
p++;
}
while(*q){
*p++=*q++;
}
#endif
#if 0
//strcmp
while(*p || *q){
if(*p != *q){
printf("%d",*p-*q);
return 0;
}
*p++;
*q++;
}
#endif
*p='\0';
puts(s);
puts(a);
return 0;
}
运行结果:

strcmp:
#include <stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
char s[20]="hello";
char a[10]="horld";
char *p=s;
char *q=a;
#if 0
//strcpy
while(*q){
*p++=*q++
}
#endif
#if 0
//strcat
while(*p){
p++;
}
while(*q){
*p++=*q++;
}
#endif
#if 1
//strcmp
while(*p || *q){
if(*p != *q){
printf("%d\n",*p-*q);
return 0;
}
*p++;
*q++;
}
#endif
*p='\0';
puts(s);
puts(a);
return 0;
}
运行结果:

本文详细介绍了如何使用指针来实现C语言中的字符串比较函数strcmp和连接函数strcat,通过代码实例展示了其实现过程,并提供了对应运行结果。
4537

被折叠的 条评论
为什么被折叠?



