作业1:mystrlen函数
![](https://img-blog.csdnimg.cn/img_convert/65e0d15620100fa8d58c659f62467aba.png)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int mystrlen(char s[]) //定义一个求字符串长度的函数
{
int i;
for(i=0;s[i]!='\0';i++); //遍历字符串直到\0结束,得出字符串长度
return i;
}
int main(int argc, const char *argv[])
{
char s[20]="hello shanghai"; //定义一个字符串
int len=mystrlen(s); //求实际长度
printf("len=%d\n",len);
return 0;
}
作业2、mystrcmp函数
![](https://img-blog.csdnimg.cn/img_convert/36e9e0b5caeafa6f5f76222900450237.png)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int mystrcmp(char *p1,char *p2)
{
if(*p1=='\0'&&*p2=='\0') //判断p1与p2是否相等
return 0;
if(*(p1)>*(p2)||*(p1)<*(p2)) //判断p1与p2的大小
return *p1-*p2;
if(*(p1)==*(p2)) // p1与p2相等时
return mystrcmp(p1+1,p2+1); //返回值为p1与p2的下一位,再次比较
}
int main(int argc, const char *argv[])
{
char s1[20];
char s2[20];
printf("输入第一个字符串:");
gets (s1);
printf("输入第二个字符串:");
gets(s2);
int cmp=mystrcmp(s1,s2);
if(cmp>0)
printf("第一个字符串大\n");
else if (cmp<0)
printf("第二个字符串大\n");
else
printf("两个字符一样大\n");
return 0;
}
作业3、mystrcat函数
![](https://img-blog.csdnimg.cn/img_convert/b28ea5b73929d57d6efa513ca06b7aa7.png)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *mystrcat(char *p,char *q)
{
int i=0,j=0;
while(p[i]!='\0')
{
i++; //得出p字符串长度
}
for(j=0;q[j]!='\0';j++)
{
p[i]=q[j]; //将字符串q加到字符串p之后
i++;
}
p[i]=q[j]; //将'\0'加到新p结尾
return p;
}
int main(int argc, const char *argv[])
{
char s1[20]="hello";
char s2[20]="worldqw";
mystrcat(s1,s2); //将字符串s2加到字符串s1之后
printf("s1=%s\n",s1);
return 0;
}
作业4、mystrcpy函数
![](https://img-blog.csdnimg.cn/img_convert/6e052993de74da62a40e04773d6c2ae5.png)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *mystrcpy(char *p,char *q)
{
int i=0,j=0;
for(j=0;q[j]!='\0';j++)
{
p[j]=q[j]; //将第二个字符串拷贝给第一个字符串
}
p[j]=q[j]; //将'\0'赋值到p结尾
return p;
}
int main(int argc, const char *argv[])
{
char s1[20]="hello";
char s2[20]="worldqw"; //定义两个字符串数组
mystrcpy(s1,s2); // 将第二个字符串拷贝给第一个数组
printf("s1=%s\n",s1);
return 0;
}