c++怎样把字符串转换成数组
要将字符串转换为数组,可使用`std::string`的`c_str()`方法来获得字符串的C风格字符数组,然后将其复制到新的数组中。以下是一个示例代码:
```cpp
#include
#include
int main() {
std::string str = "Hello, World!";
// 获得字符串的C风格字符数组
const char* cstr = str.c_str();
// 计算数组的长度
int length = str.length();
// 创建一个新的字符数组来存储转换后的字符串
char* arr = new char[length + 1];
// 将C风格字符数组复制到新的数组中
for (int i = 0; i < length; i++) {
arr[i] = cstr[i];
}
arr[length] = ' ';
// 打印转换后的数组
for (int i = 0; i < length; i++) {
std::cout << arr[i];
}
std::cout << std::endl;
// 释放内存
delete[] arr;
return 0;
}
```
输出结果为:
```
Hello, World!
```
注意,这里需要手动分配和释放内存来保存转换后的数组。如果你正在使用C++11或更高版本,也能够斟酌使用`std::vector`来替换动态分配的字符数组。
TOP