C++ 中的 strlen()
函数返回给定 C 字符串的长度。它定义在 cstring 头文件中。
示例
#include <iostream>
#include <cstring>
using namespace std;
int main() {
// initialize C-string
char song[] = "We Will Rock You!";
// print the length of the song string
cout << strlen(song);
return 0;
}
// Output: 17
strlen() 语法
strlen()
函数的语法是
strlen(const char* str);
这里,str 是我们要找出长度的 字符串,它被转换为 const char*
。
strlen() 参数
strlen()
函数接受以下参数
- str - 指向 C 字符串(以 null 结尾的字符串)的 指针,用于计算其长度
strlen() 返回值
strlen()
函数返回
- C 字符串的长度 (
size_t
)
strlen() 原型
strlen()
在 cstring 头文件中定义的原型是
size_t strlen(const char* str);
注意: 返回的长度不包括 null 字符 '\0'
。
strlen() 未定义行为
如果出现以下情况,strlen()
的行为是未定义的:
- 字符串中没有 null 字符
'\0'
,即它不是 C 字符串
示例:C++ strlen()
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char str1[] = "This a string";
char str2[] = "This is another string";
// find lengths of str1 and str2
// size_t return value converted to int
int len1 = strlen(str1);
int len2 = strlen(str2);
cout << "Length of str1 = " << len1 << endl;
cout << "Length of str2 = " << len2 << endl;
if (len1 > len2)
cout << "str1 is longer than str2";
else if (len1 < len2)
cout << "str2 is longer than str1";
else
cout << "str1 and str2 are of equal length";
return 0;
}
输出
Length of str1 = 13 Length of str2 = 22 str2 is longer than str1
另请阅读