1311

7 分钟

#C 语言标准库函数 strlen

/********************************************* * @brief 获取字符串的长度 * @param str 字符串 * @return 字符串的长度 ********************************************/ size_t strlen(const char* str);

说明

获取 str 指向的字符串的长度,长度不含结尾的 0。

参数

  • str - 要获取长度的字符串

返回值

  • 字符串的长度(不含结尾的 0)

#示例

#include <stdio.h> #include <string.h> int main(void) { printf("%zu\n", strlen("hello")); // 输出 5 printf("%zu\n", strlen("hello world")); // 输出 11 printf("%zu\n", strlen("hello \0 world")); // 输出 6,'\0' 是字符串结尾 return 0; }

说明:

  • "hello" 的长度是 5
  • "hello world" 的长度是 11
  • "hello \0 world" 的长度是 6,因此中间的 '\0' 被视为字符串结尾

运行结果:

5 11 6

#推荐阅读

#参考标准

  • C23 standard (ISO/IEC 9899:2024):
    • 7.24.6.3 The strlen function (p: TBD)
  • C17 standard (ISO/IEC 9899:2018):
    • 7.24.6.3 The strlen function (p: TBD)
  • C11 standard (ISO/IEC 9899:2011): 7.24.6.3 The strlen function (p: 372)
  • C99 standard (ISO/IEC 9899:1999):
    • 7.21.6.3 The strlen function (p: 334)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • 4.11.6.3 The strlen function

创建于 2025/7/6

更新于 2025/8/1