1、自写求字符串有效长度函数
strlen(str)-----myStrlen(str);
int myStrlen(char *str)
{
int len=0;
char *p=str;
while(*p++!='\0')
{
len++;
}
return len;
}
int main()
{
char str[]="Hello";
printf("%d\n",strlen(str));
printf("%d\n",myStrlen(str));
getchar();
return 0;
}
2、自写在字符串中查找子串首次出现的位置
strstr(str,substr)----------myStrstr(str,substr);
char *myStrstr(char *str,char *substr)
{
char *pStr=str;
char *pSubstr=substr;
while(*pStr!='\0')
{
char *p=pStr;
char *sp=pSubstr;
while(*p==*sp&&*sp!='\0')
{
p++;
sp++;
}
if(*sp=='\0')
{
break;
}
else
{
pStr++;
}
}
return pStr;
}
int main()
{
char str[]="Hello World";
char substr[]="llo";
printf("%s\n",strstr(str,substr));
printf("%s", myStrstr(str,substr));
getchar();
return 0;
}
3、自写字符串拷贝函数
strcpy(str,src)---------myStrcpy(str,src);
void myStrcpy(char *str,char *src)
{
char *pSrc=src;
char *pStr=str;
while(*pSrc!='\0')
{
*pStr++=*pSrc++;
}
}
void Print(char *str)
{
char *p=str;
while(*p!='\0')
{
printf("%c",*p++);
}
}
int main()
{
char src[]="Hello";
char str[20];
myStrcpy(str,src);
Print(str);
getchar();
return 0;
}
4、自写字符串中查找某个字符首次出现的位置函数
strchr(str,ch)---------myStrchr(str,ch);
char *myStrchr(char *str,char ch)
{
char *p=str;
while(*p!='\0'&&*p!=ch)
{
p++;
}
return p;
}
int main()
{
char str[]="Hello";
char ch='e';
printf("%s",myStrchr(str,ch));
}
5、自写字符串比较函数
strcmp(str,src)------------myStrcmp(str,src);
int myStrcmp(char *str,char *src)
{
char *pStr=str;
char *pSrc=src;
while(*pStr!='\0'||*pSrc!='\0')
{
if(*pStr==*pSrc)
{
pStr++;
pSrc++;
}
else if(*pStr>*pSrc)
{
return 1;
}
else
return -1;
}
if(*pStr!='\0'&&*pSrc!='\0')
{
return 0;
}
}
int main()
{
char *str="hello";
char *src="Hello";
printf("%d", strcmp(str,src));
printf("%d", myStrcmp(str,src));
}
6、自写字符串拼接函数
strcat(str,src)-------myStrcat(str,src);
void myStrcat(char *str,char *src)
{
char *pStr=str;
char *pSrc=src;
while(*pStr!='\0')
{
pStr++;
}
while(*pSrc!='\0')
{
*pStr++=*pSrc++;
}
*pStr='\0';
}
void Print(char *str)
{
char *p=str;
while(*p!='\0')
{
printf("%c",*p++);
}
}
int main()
{
char str[50]="Hello";
char src[]="World";
myStrcat(str,src);
Print(str);
getchar();
return 0;
}