##模拟实现strlen函数

来源:互联网 发布:小米note3网络异常 编辑:程序博客网 时间:2024/05/01 16:27

strlen函数也是字符串操作函数,是用来求字符串的长度,以‘\0’为结束标志,长度不包含’\0’这个字符,例如;

#include <stdio.h>int main(){    char arr[9] = "1234abcd";    printf("%d\n",strlen(arr));    return 0;}

最后程序运行结果如下
这里写图片描述

现在自己实现my_strlen 函数如下:

#include <stdio.h>#include <windows.h>#include <assert.h>int my_strlen(char * msg){    int count = 0;    assert(msg);    while (*msg !='\0')    {        count++;//统计字符串的长度        msg++;      }    return count;}int main(){    char msg[] = "1234abcd";    int ret = my_strlen(msg);    printf("%d\n",ret);    system("pause");    return 0;}

当然最后答案是8啦,小伙伴们,是不是很简单啦,赶紧试一试吧。

1 0