1,自定义函数my_strlen实现函数strlen的功能
#include<stdio.h>
int my_strlen(char *p)
{
if (*p=='\0')
{
return 0;
}
else
{
return 1+my_strlen(p+1);
}
}
int main()
{
printf("请输入字符串");
char arr[50]="";
char *p=arr;
scanf("%s",arr);
int num=my_strlen(p);
printf("该字符串的长度为%d\n",num);
return 0;
}
2,自定义函数my_strcpy实现函数strcpy的功能
#include<stdio.h>
void my_strcpy(char *p,const char *q)
{
for (int i = 0; i < 50; i++)
{
p[i]=q[i];
}
printf("赋值后第一个字符串为%s,第二个字符串为%s\n",p,q);
}
int main()
{
char arr[50]="",brr[50]="";
char *p=arr,*q=brr;
printf("请输入第一个字符串");
scanf("%s",p);
getchar();
printf("请输入第二个字符串");
scanf("%s",q);
getchar();
my_strcpy(p,q);
return 0;
}
3,自定义函数my_strcmp实现函数strcmp的功能
#include<stdio.h>
int my_strcmp(const char *p,const char *q)
{
int n=0;
for (int i = 0; i < 50; i++)
{
if (p[i]==q[i])
{
n=0;
continue;
}
else if(p[i]>q[i])
{
n=1;
break;
}
else
{
n=-1;
break;
}
}
return n;
}
int main()
{
char arr[50]="",brr[50]="";
char *p=arr,*q=brr;
printf("请输入第一个字符串");
scanf("%s",p);
getchar();
printf("请输入第二个字符串");
scanf("%s",q);
int n=my_strcmp(p,q);
switch (n)
{
case 1:
printf("第一个字符串大\n");
break;
case -1:
printf("第二个字符串大\n");
break;
case 0:
printf("两个字符完全一样\n");
default:
break;
}
return 0;
}
4,自定义函数my_strcat实现函数strcat的功能
#include<stdio.h>
#include<string.h>
void my_strcat(char *p,const char *q)
{
int n=strlen(p);
int m=strlen(q);
for (int i = 0; i < m; i++)
{
p[n+i]=q[i];
}
}
int main()
{
char arr[50]="",brr[50]="";
char *p=arr,*q=brr;
printf("请输入第一个字符串");
scanf("%s",p);
getchar();
printf("请输入第二个字符串");
scanf("%s",q);
getchar();
my_strcat(p,q);
printf("连接后的字符串为%s\n",p);
return 0;
}
5,自定义函数my_strstr判断字符串src是否包含字串dest
#include<string.h>
#include<stdio.h>
void my_strstr(const char *p,const char *q)
{
int n=strlen(q),m=strlen(p),x=0;
if (m>n)
{
for (int i = 0; i < m; i++)
{
if (q[x]==p[i])
{
x++;
if (x==n)
{
break;
}
}
else
{
if (x!=0)
{
x=0;
i-=1;
}
else
{
x=0;
}
}
}
}
if (x==n)
{
printf("第二个是子串\n");
}
else
{
printf("不是\n");
}
}
int main()
{
char arr[50]="",brr[50]="";
char *p=arr,*q=brr;
printf("请输入第一个字符串");
scanf("%s",p);
getchar();
printf("请输入第二个字符串");
scanf("%s",q);
getchar();
my_strstr(p,q);
return 0;
}