阅读背景:

实现my_strlen的3种方法

来源:互联网 
第1种:计数器实现

定义一个计数器,当下一个字符不是’

第1种:计数器实现

定义一个计数器,当下一个字符不是’\0’的时候就自增。

#include <stdio.h> #include <assert.h> int my_strlen(const char* p) { int count = 0; assert(p!=NULL); while (*p != '\0') { count++; p++; } return count; } 第二种:指针运算实现

利用指针减去指针等于中间元素个数,如果后一个元素不是\0计数器就自增。

#include <stdio.h> #include <assert.h> int my_strlen(const char* arr) { assert(arr != NULL); char* start = arr; char* end = arr; while (*end != '\0') { end++; str++; } return end - start; } 第三种:递归实现 int my_strlen(char* str) { assert(str != NULL); if (*str=='\0') return 0; return my_strlen(str + 1) + 1; }
’的时候就自增。

#include <stdio.h> #include <assert.h> int my_strlen(const char* p) { int count = 0; assert(p!=NULL); while (*p != '
第1种:计数器实现

定义一个计数器,当下一个字符不是’\0’的时候就自增。

#include <stdio.h> #include <assert.h> int my_strlen(const char* p) { int count = 0; assert(p!=NULL); while (*p != '\0') { count++; p++; } return count; } 第二种:指针运算实现

利用指针减去指针等于中间元素个数,如果后一个元素不是\0计数器就自增。

#include <stdio.h> #include <assert.h> int my_strlen(const char* arr) { assert(arr != NULL); char* start = arr; char* end = arr; while (*end != '\0') { end++; str++; } return end - start; } 第三种:递归实现 int my_strlen(char* str) { assert(str != NULL); if (*str=='\0') return 0; return my_strlen(str + 1) + 1; }
') { count++; p++; } return count; } 第二种:指针运算实现 #include <s



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: