您的位置:首页 > 其它

字符串复制和比较函数的实现

2015-10-27 11:07 363 查看
#include<stdio.h>
#include<string.h>

#define N 50

//字符串复制函数1,数组法(用虚数组做形参,以下标法访问元素)
void strcpy1(char s1[], char s2[])
{
int i = 0;
while(s1[i] = s2[i])
i++;
}
//字符串复制函数2,指针法(用字符指针做形参,以指针法访问元素)
void strcpy2(char *s1, char *s2)
{
while(*s1++ = *s2++);
}

//字符串比较函数,数组法
int strcmp1(char s1[], char s2[])
{
int i= 0;
while(s1[i] == s2[i])
{
if(s1[i] == 0)
return 0;
i++;
}
return (s1[i] - s2[i]);
}
//字符串比较函数,指针法
int strcmp2(char *s1, char *s2)
{
while(*s1 == *s2)
{
if(*s1 == 0)
return 0;
s1++;
s2++;
}
return (*s1 - *s2);
}
int main(void)
{
char str1[] = "welcome to Hello World!", str2
, str3
;
char st1[] = "welcome to China!", st2[] = "welcome to hello world!";

strcpy1(str2, str1);
puts(str2);
printf("************************\n");
strcpy2(str3, str1);
puts(str3);
printf("************************\n");
strcpy1(str2 + 11, "Beijing");
puts(str2);
printf("************************\n");
printf("str1: ");
puts(str1);
printf("st1: ");
puts(st1);
printf("st2:");
puts(st2);
printf("\nstr1与st1的比较结果:%d\n",strcmp1(str1, st1));
printf("\nstr1与st2的比较结果:%d\n",strcmp2(str1, st2));
printf("\nstr1与str2的比较结果:%d\n",strcmp2(str1, str2));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: