大佬教程收集整理的这篇文章主要介绍了C语言-字符串函数的实现(一)之strlen,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
C语言中的字符串函数有如下这些
接下来看看如何实现它们
我们看看文档是怎样说的,如下
size_t strlen ( const char * str );
Get String length
获取字符串长度
Returns the length of the C String str.
返回C字符串str的长度
The length of a C String is determined by the terminaTing null-character: A C String is as long as the number of characters between the beginning of the String and the terminaTing null character (without including the terminaTing null character itself).
C字符串长度是由'\0'来确定的,也就是说从字符串的第一个开始只要遇到'\0'就结束长度计算(不包含'\0')
This should not be confused with the size of the array that holds the String. For example:
不用困惑你创建的数组的大小,比如这样
char mystr[100]="test String";
defines an array of characters with a size of 100
char
s, but the C String with which @H_363_64@mystr has been initialized has a length of only 11 characters. Therefore, whilesizeof(mystr)
evaluates to100
,strlen(mystr)
returns11
.定义一个大小为100的数组@H_200_84@mystr,然后@H_200_84@mystr 就已经被初始化为一个长度为11的字符串了。所以呢,
sizeof(mystr)
会得出100
, 而strlen(mystr)
会返回11
.
综上,可以知道
strlen函数的实现有好几种。
比如
接下来一一实现。
断言指针不为空是个好习惯~
int my_strlen(char* str)
{
int count = 0;
assert(str != null);
while (*str != '\0') // while (*str)
{
count++;
str++;
}
return count;
}
就一直找'\0',当*str不是'\0'时,就count++,str++,直到遇到'\0'停止,然后返回count就是长度了。
断言指针不为空是个好习惯~
int my_strlen(char* str)
{
assert(str != null);
char* p = str;
while(*p == '\0')
{
return 0;
}
return 1 + my_strlen(p + 1);
}
比如传入的str地址为 1000
那么 1 + my_strlen(p + 1) 中,p + 1,指针偏移后就是1001,以此类推。
1 + 1 + my_strlen(p + 1)
1 + 1 + 1 + my_strlen(p + 1)
1 + 1 + 1 + 1 + my_strlen(p + 1)
...
1 + 1 + 1 + 1 + ... + 0
最终就可以得出长度。
断言指针不为空是个好习惯~
int my_strlen(char* str)
{
assert(str != null);
char* p = str;
while (*p != '\0')
{
p++;
}
return p - str;
}
把指针str的地址赋值给一个新的指针p,str作为指向起始地址的指针,不改变它,记录起始地址。
然后通过指针p进行查找'\0',判断当前字符是否为'\0',不是就进行p++,然后继续判断下一个字符,如此循环,直到指针p找到'\0',然后用 当前的指针p@H_489_190@ 减去 起始指针str@H_489_190@ 进行返回,就是长度了。
最后,谢谢你看到这里,谢谢你认真对待我的努力,希望这篇博客有帮到你
你轻轻一个赞,就是我世界里的一颗星
还有因本人水平有限,如有错误以及不足之处,欢迎靓仔靓女们
指出。
以上是大佬教程为你收集整理的C语言-字符串函数的实现(一)之strlen全部内容,希望文章能够帮你解决C语言-字符串函数的实现(一)之strlen所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。