C language library functions are many, here I realize simulation for a few string functions:
1, find the string length function strlen
- Function prototype: unsigned int strlen (const char STR);
2, strcpy string copy function
- Function prototype: extern char * strcpy (char * dest, char * src)
3, strcat string concatenation function
- Function prototype: char * strcat (char * strDest, const char * strScr)
4, strstr string search function
- Function prototype: char * strstr (char str, char substr)
5, strcmp string comparison functions
- Function prototype: int strcmpa (const char * str1, const char * str2)
char* my_strcpy(char* dst, const char* src) //字符串拷贝
{
assert(dst&&src);
while (*src)
{
*dst = *src;
src++;
dst++;
}
*dst='\0';
return dst;
}
int my_strlen(const char*str) //求字符串长度
{
assert(str);
int sum = 0;
while (*str++ != '\0')
{
sum++;
}
return sum;
}
char* my_strcat(char* dst, const char* src) //字符串连接
{
// hello worldll
assert(dst&&src);
while (*dst != '\0')
{
dst++;
}
while (*src != '\0')
{
*dst++ = *src++;
}
*dst = '\0';
return dst;
}
int my_strcmp(const char* dst, const char* src) //字符串比较
{
int len = 0;
assert(dst&&src);
while (*dst&&*src && (*dst == *src))
{
++dst;
++src;
}
return *dst-*src;
}
char* strstr(const char*dst, const char* src) //字符串查找
{
assert(dst&&src);
while (*dst)
{
while ((*dst != *src) && *dst!='\0')
{
++dst;
}
while (*dst == *src)
{
const char *dest = dst;
const char *srcs = src;
while (*dest == *srcs)
{
++dest;
++srcs;
}
if (*srcs == '\0')
{
return (char*)dst;
}
else
{
dst++;;
}
}
}
}