目录
概述
对于字符串操作的库函数有很多,但是到底是怎样实现的呢,以下内容将对这些库函数的进行代码实现。
注:以下部分函数使用了断言来预防出现空指针,如有报错可添加头文件 #include<assert.h>
函数实现
strlen
求字符串长度
代码:
#include<assert.h>
size_t my_strlen(const char*str)
{
int count = 0;
assert(str != NULL);
while (*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
char arr[] = "asdfg";
int len = my_strlen(arr);
printf("%d\n", len);
return 0;
}
strcpy
拷贝字符串
代码:
#include<assert.h>
char* my_strcpy(char* dest, const char* src)
{
assert(src && dest);
char* ret = dest;
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = { 0 };
char arr2[] = "hello world";
my_strcpy(arr1, arr2);
printf("%s\n", arr1);
return 0;
}
strcat
追加字符串
代码:
char* my_strcat(char* dest, char* src)
{
assert(dest && src);
char* ret = dest;
while (*dest)
{
dest++;
}
while (*dest++ = *src++)
{
;
}
return ret;
}
int main()
{
char arr1[20] = "Hello";
char arr2[] = " world";
my_strcat(arr1,arr2);
printf("%s\n", arr1);
return 0;
}
strcmp
比较字符串大小
代码:
int my_strcmp(const char* s1, char* s2)
{
assert(s1 && s2);
while (*s1 == *s2)
{
if (*s2 == '\0')
{
return 0;
}
s1++;
s2++;
}
//if (*s1 < *s2)
//{
// return -1;
//}
//if (*s1 > *s2)
//{
// return 1;
//}
return (*s1 - *s2);
}
int main()
{
char arr1[] = "asdfg";
char arr2[] = "asdfghj";
int ret = my_strcmp(arr1, arr2);
if (ret > 0)
printf("arr1>arr2");
else if(ret<0)
printf("arr1<arr2");
else
printf("arr1=arr2");
return 0;
}
strstr
查找字符串(在另一个字符串中查询当前字符串是否为其字串)
代码:
#include<string.h>
#include<assert.h>
char* my_strstr(const char* str1,const char* str2)
{
assert(str1 && str2);
const char* s1 = str1;
const char* s2 = str2;
const char* cur = str1;
while (*cur)
{
s1 = cur;
s2 = str2;
while (*s1&&*s2&&(*s1 == *s2))
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return (char*)cur;
}
cur++;
}
return NULL;
}
int main()
{
char arr1[20] = "adfdgasdf";
char arr2[] = "asd";
char*p=my_strstr(arr1, arr2);
if (NULL == p)
{
printf("找不到子串\n");
}
else
{
printf("%s\n", p);
}
return 0;
}