声明:以下代码可能并非最佳方法,若有错误疑问欢迎提出!!!
strlen函数
#include<stdio.h>
#include<string.h>
int mylen(char *str)
{
int cnt=0;
while(str[cnt]!='\0')
cnt++;
return cnt;
}
int main()
{
char s[]="hello";
printf("%d\n",mylen(s));
printf("%d",strlen(s));
return 0;
}
strcpy函数
#include<stdio.h>
#include<string.h>
char* mycpy(char *p,const char *q)
{
char *a=p;
while(*q!=NULL)
*p++=*q++;
*p='\0';//p已经移动到最后一位,需要一个变量能找到它的地址,该变量就是a
return a;
}
int main()
{
char q[]="hello";
char p[]="\0";
printf("%s\n",mycpy(p,q));
printf("%s",strcpy(p,q));
return 0;
}
strcmp函数
/*
主要思想是遍历两个字符串的相同部分,直到不同时比较不同字符的大小;
*/
#include<stdio.h>
#include<string.h>
int mycmp(char *p,char *q)
{
while(*p==*q&&*p!='\0')
{
p++;
q++;
}
if(*p-*q>0)
return 1;
if(*p-*q<0)
return -1;
if(*p-*q==0)
return 0;
}
int main()
{
char p[]="hello";
char q[]="hi";
printf("%d\n",mycmp(p,q));
printf("%d",strcmp(p,q));
return 0;
}
strcat函数
#include<stdio.h>
#include<string.h>
char *mycat(char *p,char *q)
{
char *a=p;
while(*p!='\0')
p++;
while(*q!=NULL)
*p++=*q++;
return a;
}
int main()
{
char q[]="world!!!";
char p[]="hello ";
printf("%s\n",mycat(p,q));
// printf("%s",strcat(p,q));
return 0;
}
strrev函数
/*
思路参考顺序链表的逆置函数inversion
*/
#include<stdio.h>
#include<string.h>
char *myrev(char *str)
{
int top=0;
int bottom=-1;
char *a=str;
char t;
while(*a!='\0')
{
a++;
bottom++;
}
while(top<bottom)
{
t=str[top];
str[top]=str[bottom];
str[bottom]=t;
top++;
bottom--;
}
return str;
}
int main()
{
char a[]="hello";
printf("%s\n",myrev(a));
printf("%s",strrev(a));
return 0;
}