如何strlen()
内部工作?该功能是否存在固有的错误?
strlen
通常通过计算字符串中的字符直到\0
字符被发现。规范的实现是:
size_t strlen (char *str) {
size_t len = 0;
while (*str != '\0') {
str++;
len++;
}
return len;
}
至于函数中可能存在的固有错误,不存在 - 它的工作原理与文档完全一致。这并不是说它没有某些问题,即:
- if you pass it a "string" that doesn't have a
\0
at the end, you may run into problems but technically, that's not a C string (a) and it's your own fault.
- 你不能放
\0
字符串中的字符,但同样,在这种情况下它不会是 C 字符串。
- 这不是最有效的方法 - 您可以预先存储长度,这样您就可以更快地获得长度。
但这些都不是错误,它们只是设计决策的结果。
关于最后一点,另请参阅这篇优秀的文章 http://www.joelonsoftware.com/articles/fog0000000319.html作者:Joel Spolsky,他讨论了各种字符串格式及其特征,包括普通的 C 字符串(带有终止符)、Pascal 字符串(带有长度)以及两个以空结尾的 Pascal 字符串的组合。
尽管他对最终类型有一个更“丰富多彩”的术语,我们可以说,每当我想到 Python 优秀的(并且完全不相关的)f 字符串时,这个术语就会经常浮现在我的脑海中:-)
(a) A C string is defined as a series of non-terminator characters (any character other than \0
) followed by a terminator. Hence this definition disallows both embedded terminators within the sequence, and sequences without such a terminator. Or, putting it more succinctly (as per the ISO C standard):
字符串是由第一个空字符终止并包含第一个空字符的连续字符序列。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)