目录
1 strlen
1.1计数器法
#include<stdio.h> #include<assert.h> int my_strlen(const char* arr) { int a = 0; assert(arr != NULL); while (*arr++ != '\0') { a++; } return a; } int main() { char arr[] = "abcdef"; int len = my_strlen(arr); printf("%d\n", len); }
1.2递归的方法
#include<stdio.h> #include<assert.h> int my_strlen(const char* arr) { assert(arr != NULL); if (*arr == '\0') { return 0; } return my_strlen(++arr)+1; } int main() { char arr[] = "abcdef"; int len = my_strlen(arr); printf("%d\n", len); }
3. 指针-指针的方法
#include<stdio.h> #include<assert.h> int my_strlen(const char* arr) { char* p; p = arr; assert(arr != NULL); while(*p != '\0') { p++; } return p-arr; } int main() { char arr[] = "abcdef"; int len = my_strlen(arr); printf("%d\n", len); }
2.strcpy
#include<stdio.h> #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 bit"; printf("%s\n", my_strcpy(arr1, arr2)); return 0; }
3.strcat
#include<stdio.h> #include<assert.h> #include<string.h> char* my_strcat(char* dest, char* src) { assert(dest && src); int n = strlen(dest); do{ *(dest + n) = *(src); n++; } while (*src++ != '\0'); return dest; } int main() { char arr1[20] = "hello"; char arr2[] = " bit"; printf("%s\n", my_strcat(arr2, arr2)); return 0; }
4.strcmp
int my_strcmp(const char* s1, const char* s2) { assert(s1 && s2); while (*s1 == *s2) { if (*s1 == 0) return 0; s1++; s2++; } if (*s1 > *s2) return 1; else return -1; } int main() { char arr1[] = "abcd"; char arr2[] = "abdc"; int ret = my_strcmp(arr1, arr2); if (ret >0) { printf(">\n"); } else if (ret == 0) { printf("== \n"); } else { printf("<\n"); } printf("%d\n", ret); return 0; }
5.strstr
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[] = "abbbcdef"; char arr2[] = "bbc"; char* ret = my_strstr(arr1, arr2); if (NULL == ret) { printf("找不到子串\n"); } else { printf("%s\n", ret); } return 0; }