strlen的模拟实现

来源:互联网 发布:java与 编辑:程序博客网 时间:2024/06/07 15:25

strlen函数的功能是计算计算字符串中字符的个数(到‘\0’结束,不包括‘\0’)

下面我们进行strlen的模拟实现:

#define _CRT_SECURE_NO_WARNINGS 1#include<stdio.h>#include<assert.h>size_t my_strlen(const char* str)//size_t为一个unsigned类型  //const在这里可防止指针中内容被改变{int count = 0;assert(str != NULL);//断言str不为空指针while (*(str++) != '\0')//当遇到'0'时停止{count++;}return count;}int main(){char arr[20] = "abcdefg";printf("%s has %d chars.\n", arr, my_strlen(arr));system("pause");return 0;}

输出结果为:


0 0
原创粉丝点击