#include<stdio.h>
#include<string.h>
#include<assert.h>
//int my_strcmp(const char* str1, const char* str2)
//{
// assert(str1 && str2);//指针有效性,不能为空指针
// while (*str1 == *str2)
// {
// if (*str1 == '\0')
// return 0;//相等的情况
// str1++;
// str2++;
// }
// if (*str1 > *str2)
// return 1;
// else (*str1 < *str2)
// return -1;
//}
//简化
int my_strcmp(const char* str1, const char* str2)
{
assert(str1 && str2);//指针有效性,不能为空指针
while (*str1 == *str2)
{
if (*str1 == '\0')
return 0;//相等的情况
str1++;
str2++;
}
return(*str1 - *str2);
}
int main()
{
char arr1[] = "abcde";
char arr2[] = "abcf";
int ret = my_strcmp(arr1, arr2);
if (ret < 0)
printf("<");
if (ret == 0)
printf("==");
if (ret> 0)
printf(">");
return 0;
}
效率比较低
char* my_strstr(const char* str1, const char* str2)
{
assert(str1 && str2);
const char* s1 = str1;
const char* s2 = str2;
const char* p = str1;
while (*p)
{
s1 = p;
s2 = str2;
while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2)
{
s1++;
s2++;
}
if (*s2 == '\0')
{
return(char*)p;
}
p++;
return NULL;
}
}
int main()
{
char email[] = "zpw@bitejiuyeke.com";
char substr[] = "bitejiuyeke";
char* ret = my_strstr(email, substr);
if (ret == NULL)
{
printf("子串不存在\n");
}
else
{
printf("%s\n", ret);
}
return 0;
}
KMP算法
这个算法也是用来实现一个字符串中查找字符串的
效率高,但实现难度大
B站搜索:比特大博哥,可以找到KMP算法实现
strtok 切
int main()
{
const char* sep = "@.";
char email[] = "zhangpengwei@bitjiuyeke.com";
char cp[30] = { 0 };
//strcpy(cp, email);
//char* ret = strtok(cp, sep);
//printf("%s\n", ret);
//char* ret = strtok(NULL, sep);
//printf("%s\n", ret);
//char* ret = strtok(NULL, sep);
//printf("%s\n", ret);
//简化
char* ret = NULL;
for (ret = strtok(cp, sep); ret != NULL; ret = strtok(NULL, sep))
{
printf("%s\n", ret);
}
return 0;
}
///memcpy两块独立数据之间的拷贝函数,不能对同一块空间重叠拷贝与之对应的memmove
void* my_memcpy(void* dest, const void* src, size_t num)
{
assert(dest && src);
void* ret = dest;
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)dest + 1;
}
return ret;
}
int main()
{
int arr1[] = { 1,2,3,4,5,6,7 };
int arr2[10] = { 0 };
my_memcpy(arr2, arr1, 28);
return 0;
}