c++中如何将string转换为char[]
时间: 2023-12-28 19:04:16 浏览: 34
可以通过以下两种方法将string类型转换为char[]类型:
1.使用c_str()函数:
```c++
string str = "hello";
const char* charArray = str.c_str();
```
2.使用strcpy()函数:
```c++
string str = "hello";
char charArray[6]; // 需要给数组分配足够的空间,包括字符串结尾的'\0'
strcpy(charArray, str.c_str());
```
需要注意的是,使用第二种方法时需要保证char[]数组足够大,包括字符串结尾的'\0',否则可能导致内存溢出。
相关问题
c++将string转换为char*
以下是两种将C++中的string转换为char*的方法:
1. 使用string的copy函数:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
char *ptr = new char[str.size() + 1]; // 加上字符串结束标志 '\0'
str.copy(ptr, str.size() + 1);
std::cout << ptr << std::endl;
delete[] ptr;
return 0;
}
```
2. 使用string的c_str函数:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
const char *ptr = str.c_str();
std::cout << ptr << std::endl;
return 0;
}
```
C++将string转换为char数组
可以使用string类中的c_str()函数将string类型转换为char数组。
例如:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World!";
char char_arr[str.size() + 1]; // 加1是为了给'\0'留出空间
strcpy(char_arr, str.c_str()); // 使用c_str()函数将string类型转换为char数组
cout << char_arr << endl;
return 0;
}
```
输出结果为:
```
Hello World!
```
需要注意的是,使用c_str()函数返回的指针指向的是一个临时的字符数组,其生命周期与string对象相同。因此,如果在char数组中需要长期保存string对象中的内容,需要将其复制到新的内存空间中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)