模拟实现函数strlen

先看strlen函数的原型size_t strlen( const char *string );具体参数解释查看MSDN

它是常用的字符串函数,用来统计字符串中字符的个数(不包含末尾的‘\0’).举个例子看一下strlen的用法

#include<stdio.h>
#include<string.h>
int main()
{
  char a[]="hello";
  printf("strlen(a)=%d\n",strlen(a));
  printf("sizeof(a)=%d\n",sizeof(a));
  return 0;
}

输出结果:strlen(a)=5

                    sizeof(a)=6

可见strlen函数在统计字符个数时并没有把字符串末尾的‘\0’包含进去,那么我们可以试着模拟实现strlen函数。

方案一:采用设置计数器的方法,初始值设为0,用指针或者数组下标的方法遍历字符串,一边遍历一边检查是否已经到了‘\0’,相应的计数器的值自增。直到遇到‘\0’,这时候计数器的值即为字符串长度

#include<stdio.h>
int my_strlen(const char*str)
{
   int cnt = 0;//设置计数器
   while (*str != '\0')
   {
	   cnt++;
	   str++;
   }
   return cnt;
}

int main()
{
   char a[] = "hello";
   printf("%d\n", my_strlen(a));
   return 0;
}

这里也可以采用数组下标来进行遍历

int my_strlen(const char*str)
{
   int idx = 0;
   while (str[idx] != '\0')
   {
	   idx++;
   }
   return idx;
}

方案二:采用指针相减的方法。先用一个指针变量保存字符串的起始位置,然后另一个指针变量不断进行移动,遍历字符串,直至遇到‘\0’,最后两个指针相减的值即为字符串长度。

int my_strlen(const char*str)
{
  const char*start = str;
  while (*str != '\0')
  {
	  str++;
  }
  return str - start;
}

但是这些代码的初衷都是通过遍历字符串实现计数的,复杂度为O(n),在StackOverflow上看到这个话题的讨论,评论中一位网友给出的一篇博客链接详细剖析了strlen的优化及相关知识。写的很不错,推荐看一下

附上链接http://www.stdlib.net/~colmmacc/2009/03/01/optimising-strlen/

猜你喜欢

转载自blog.csdn.net/melody_1016/article/details/81589394