目录
一、模拟实现strlen
二、模拟实现strcpy
三、模拟实现strcmp
四、模拟实现strcat
五、模拟实现strstr
- 模拟实现strlen
- 模拟实现strcpy
- 模拟实现strcmp
- 模拟实现strcat
- 模拟实现strstr
一、模拟实现strlen
- strlen函数是用来求字符串长度的函数
#include <stdio.h>int my_strlen(const char* str)
{char* sp = str;while (*sp){sp++;}return sp-str;
}int main()
{char arr[] = "hello";int ch = my_strlen(arr);printf("%d\n", ch);return 0;
}
二、模拟实现strcpy
- strcpy是用来实现字符串拷贝的
#include <stdio.h>
#include <assert.h>char* my_strcpy(char* str1, const char* str2)
{assert(str1 && str2);char* cp = str1;while (*str2){*str1 = *str2;str1++;str2++;}return cp;
}int main()
{char arr1[20] = {0};char arr2[] = "hello world";my_strcpy(arr1, arr2);printf("%s\n", arr1);printf("%s\n", arr2);return 0;
}
三、模拟实现strcmp
- strcmp是用来实现比较两个字符串大小的函数
#include <stdio.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++;}return *str1 - *str2;
}int main()
{char arr1[] = "abcdef";char arr2[] = "abzd";//比较两个字符串大小int ch = my_strcmp(arr1, arr2);if (ch < 0){printf("arr1小于arr2\n");}else if (ch == 0){printf("arr1等于arr2\n");}elseprintf("arr1大于arr2\n");return 0;
}
四、模拟实现strcat
- strcat是实现在一个字符串后追加一个字符串的函数
#include <stdio.h>char* my_strcat(char* str1, const char* str2)
{char* cp = str1;while (*str1){str1++;}while (*str2){*str1 = *str2;str1++;str2++;}return cp;
}int main()
{char arr1[20] = "hello ";char arr2[] = "world!";my_strcat(arr1, arr2);printf("%s\n", arr1);return 0;
}
五、模拟实现strstr
- strstr是用来实现字符串查找的
#include <stdio.h>char* my_strstr(const char* str1, const char* str2)
{char* s1 = str1;char* s2 = str2;char* cp = str1;while (*cp){s1 = cp;s2 = str2;while (*s1 != '\0' && *s2 != '\0' && *s1 == *s2){s1++;s2++;}if (*s2 == '\0'){return cp;}elsecp++;}return NULL;
}int main()
{char arr1[20] = "abbbcdef";char arr2[20] = "bbc";char* ch = my_strstr(arr1, arr2);printf("%s", ch);return 0;
}