求字符串的长度C++
时间: 2024-02-18 10:25:40 浏览: 38
你可以使用C++中的标准库函数`strlen`来获取字符串的长度。`strlen`函数需要包含`<cstring>`头文件。
下面是一个示例代码:
```cpp
#include <iostream>
#include <cstring>
int main() {
char str[] = "Hello, World!";
int length = strlen(str);
std::cout << "字符串的长度为: " << length << std::endl;
return 0;
}
```
运行这段代码,输出将会是:
```
字符串的长度为: 13
```
这里假设你要求的字符串是一个以null字符结尾的C风格字符串。如果字符串是C++的`std::string`对象,你可以使用`length()`成员函数来获取长度,例如:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
int length = str.length();
std::cout << "字符串的长度为: " << length << std::endl;
return 0;
}
```
运行这段代码,输出同样会是:
```
字符串的长度为: 13
```
相关问题
string中求字符串长度c++
在 C++ 中,可以使用 `std::string` 的 `length()` 或 `size()` 方法来获取字符串的长度。以下是示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
int length = str.length(); // 或者使用 str.size();
std::cout << "字符串长度: " << length << std::endl;
return 0;
}
```
上述代码中,我们创建了一个名为 `str` 的 `std::string` 对象,并使用 `length()` 方法获取字符串的长度。然后,我们将结果打印到控制台上。输出将是:
```
字符串长度: 13
```
c++怎么求字符串长度
在C++中,可以使用标准库中的`strlen()`函数来求字符串长度。该函数需要传入一个指向字符串的指针作为参数,返回该字符串的长度,不包括字符串末尾的空字符`\0`。
以下是一个示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "hello world";
int len = strlen(str);
cout << "The length of the string is: " << len << endl;
return 0;
}
```
输出结果为:
```
The length of the string is: 11
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)