admin 管理员组

文章数量: 1086019


2024年4月17日发(作者:以下不属于弥补openssl)

c++字符串长度计算

在C++中,字符串长度的计算是非常常见的操作。可以使用不同

的方法来计算字符串的长度,下面介绍两种常用的方法:

1. 使用标准库函数

C++标准库中提供了一个函数strlen(),可以用来计算一个以

null结尾的字符串的长度。这个函数的原型如下:

size_t strlen(const char *s);

其中,s是一个指向以null结尾的C字符串的指针。

示例代码:

#include

#include

using namespace std;

int main()

{

char str[] = 'Hello, world!';

size_t len = strlen(str);

cout << 'The length of the string is ' << len << endl;

return 0;

}

输出结果:

The length of the string is 13

2. 使用循环计算

- 1 -

另一种计算字符串长度的方法是通过循环遍历字符串中的每个

字符,并计数非null字符的个数。当遇到null字符时,循环终止,

得到字符串的长度。

示例代码:

#include

using namespace std;

int main()

{

char str[] = 'Hello, world!';

int len = 0;

while (str[len] != '0')

len++;

cout << 'The length of the string is ' << len << endl;

return 0;

}

输出结果:

The length of the string is 13

无论使用哪种方法,都可以得到字符串的长度。但需要注意的是,

在使用第二种方法时需要保证字符串以null结尾,否则会导致循环

不会停止,从而引起错误。

- 2 -


本文标签: 字符串 长度 方法 计算