法一:一般方法
#include<stdio.h> #include<stdlib.h> int my_strlen(const char *str) { int count = 0; while (*str++ != ‘\0‘) { ++count; } return count; } int main() { char *p = "hello"; int ret = my_strlen(p); printf("%d\n",ret); system("pause"); return 0; }
结果:
5
法二:递归
#include<stdio.h> #include<stdlib.h> int my_strlen(const char *str) { if (*str == ‘\0‘) return 0; else return 1 + my_strlen(str + 1);//先保存每一个字节的地址,在从最后一个字节开始向前求字节 } int main() { char *p = "hello"; int ret = my_strlen(p); printf("%d\n",ret); system("pause"); return 0; }
时间: 2024-08-03 15:30:09