1.strlen()
int my_strlen(const char *s)
{
int len=0;
if(s==NULL)
{
printf("error: null pointer...\n");
len=-1;
goto end;
}
while(*s++!='\0')
{
len++;
}
end:
return len;
}
2.strcpy()
char *my_strcpy(char *dest,const char *src)
{
char *tmp=dest;
if(dest==NULL||src==NULL)
{
printf("error: null pointer...\n");
tmp=NULL;
goto end;
}
while((*dest++ = *src++)!='\0'); //不考虑溢出
end:
return tmp;
}
3.strcat()
char *my_strcat(char *dest,const char *src)
{
char *tmp=dest;
if(dest==NULL||src==NULL)
{
printf("error: null pointer...\n");
tmp=NULL;
goto end;
}
while(*(++dest) != '\0'); //指向目标字符串的结尾空字符
while((*dest++ = *src++) != '\0');
end:
return tmp;
}
4.strcmp()
char my_strcmp(const char *s1,const char s2) //其实就是返回第一个不相等的字符的ASCII码差值
{
char value=0;
if(s1==NULL||s2==NULL)
{
printf("error: null pointer...\n");
value=-128;
goto end;
}
while(*s1!='\0' && *s2!='\0' && (value=*s1-*s2)==0) //逐个字符比较,如果没比较还没进行到末尾且当前比较的两个字符相等,则继续比下去
{
s1++;
s2++;
}
if(value==0 && !(*s1==0 && *s2==0)) //考虑s1包含s2或s2包含s1的情况
{
value=*s1-*s2;
}
end:
return value;
}
5.strchr()
char *my_strchr(const char *src,char ch)
{
if(src==NULL)
{
printf("error: null pointer...\n");
return NULL;
}
while(*src++ != '\0')
{
if(*src==ch)
{
return src;
}
}
}
6.strstr()
char *my_strstr(const char *s1,const char *s2)
{
if(s1==NULL||s2==NULL)
{
printf("error: null pointer...\n");
goto end;
}
while(*s1++ != '\0') //长字符串只需一轮遍历
{
char *s1_tmp=s1;
char *s2_tmp=s2;
int flag=0;
while(*s1_tmp++!='\0'&&*s2_tmp++!='\0')
{
if(*s1_tmp!=*s2_tmp) //每小轮比较中,如果对应有字符不相等,则标记
{
flag=1;
}
}
if(flag==0 && *s2_tmp=='\0') //如果小字符串遍历了且没有标记,说明找到了相等的子字符串
{
return s1;
}
}
end:
return NULL;
}