【C】库函数之 strlen

目录

1. Get string length

2. 四 种实现 strlen 函数的方法

2.1 创建临时变量作为计数器计数

2.2 指针 - 指针

2.3 递归

2.4 一行代码实现 strlen

3. 主函数

4. 输出结果


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]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值