获取字符串长度的函数,c++
时间: 2024-05-15 11:12:17 浏览: 120
在 C++ 中,可以使用 `strlen` 函数来获取字符串的长度。该函数需要传入一个字符数组(或指向字符数组的指针)作为参数,返回一个整数,表示该字符串的长度(不包括字符串末尾的空字符 '\0')。例如:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "Hello, world!";
int len = strlen(str);
cout << "Length of the string: " << len << endl;
return 0;
}
```
输出:
```
Length of the string: 13
```
另外,如果你使用的是 C++11 或更高版本的标准,也可以使用字符串类型 `std::string` 的 `length` 方法来获取字符串长度。例如:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
int len = str.length();
cout << "Length of the string: " << len << endl;
return 0;
}
```
输出:
```
Length of the string: 13
```
相关问题
c++中获取字符串长度的函数
在 C++ 中,可以使用标准库中的 `strlen()` 函数来获取 C 风格字符串的长度,但是对于 C++ 中的 `std::string` 类型的字符串,应该使用 `length()` 或 `size()` 成员函数来获取字符串的长度。
使用 `strlen()` 函数获取 C 风格字符串的长度,需要包含头文件 `cstring`,示例如下:
```c++
#include <cstring>
#include <iostream>
int main() {
char str[] = "Hello, world!";
int len = strlen(str);
std::cout << "字符串长度为:" << len << std::endl;
return 0;
}
```
输出结果为:
```
字符串长度为:13
```
对于 `std::string` 类型的字符串,可以使用 `length()` 或 `size()` 成员函数来获取字符串的长度,示例如下:
```c++
#include <string>
#include <iostream>
int main() {
std::string str = "Hello, world!";
int len = str.length(); // 或者 int len = str.size();
std::cout << "字符串长度为:" << len << std::endl;
return 0;
}
```
输出结果同样为:
```
字符串长度为:13
```
需要注意的是,对于 `std::string` 类型的字符串,使用 `length()` 或 `size()` 函数返回的类型是 `std::string::size_type`,而不是 `int`。因此,应该将结果赋值给 `std::string::size_type` 类型的变量。
获取字符串长度 c++
要获取字符串长度,可以使用C++中的`strlen()`函数。这个函数可以返回一个字符串的字符数(不包括终止符'\0')。下面是一个示例代码:
```cpp
#include <iostream>
#include <cstring>
int main() {
char str[] = "Hello, world!";
int length = strlen(str);
std::cout << "字符串长度为: " << length << std::endl;
return 0;
}
```
运行这段代码,将会输出字符串的长度为13。