目录
1. Get string length
#include <string.h>
size_t strlen ( const char * str );
Returns the length of the C string 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).
上述内容是 cplusplus 对 strlen 函数的介绍,
可以看出 strlen 函数用于 计算字符串的长度,与字符串开头和终止空字符之间的字符数相同(不包括终止空字符本身)。
2. 四 种实现 strlen 函数的方法
2.1 创建临时变量作为计数器计数
size_t Strlen(const char *src) {
assert(NULL != src);
size_t s_len = 0;
while ('\0' != *src++)
++s_len;
return s_len;
}
2.2 指针 - 指针
size_t Strlen(const char *start) {
assert(NULL != start);
const char *end = start;
while ('\0' != *end)
++end;
return end - start;
}
2.3 递归
size_t Strlen(const char *src) {
assert(NULL != src);
if ('\0' == *src)
return 0;
else
return 1 + Strlen(src + 1);
}
2.4 一行代码实现 strlen
利用逗号表达式以及三目操作符即可实现,实际上还是递归。
size_t Strlen(const char *src) {
return assert(NULL != src), ('\0' == *src) ? 0 : (1 + Strlen(src + 1));
}
3. 主函数
#include <stdio.h>
#include <assert.h>
#define EMPTY_SRC ""
#define SRC "hello"
void test() {
printf("call Strlen, src and len: [%s, %ld]\n", EMPTY_SRC, Strlen(EMPTY_SRC));
printf("call Strlen, src and len: [%s, %ld]\n", SRC, Strlen(SRC));
}
int main(void) {
test();
return 0;
}
4. 输出结果
call Strlen, src and len: [, 0]
call Strlen, src and len: [hello, 5]