char*转为string
时间: 2024-03-09 09:42:03 浏览: 26
char*转为string可以使用string的构造函数或者赋值操作符。下面是两种方法的示例:
1. 使用构造函数:
```cpp
char* cstr = "Hello";
string str(cstr);
```
2. 使用赋值操作符:
```cpp
char* cstr = "World";
string str = cstr;
```
这两种方法都可以将char*类型转换为string类型。
相关问题
const char*转char*
你好!关于 const char* 转 char*,可以通过强制类型转换来实现。具体方法如下:
```C
const char* const_str = "const string";
char* str = (char*) const_str; // 使用强制类型转换将 const char* 转为 char*
```
需要注意的是,使用强制类型转换来去除 const 属性可能会引发未定义行为,因此应该尽量避免这样的做法,除非确实有必要这样做。
另外,如果 const char* 实际上指向的是一个字符数组,那么也可以先将字符数组转为 char*,然后再去除 const 属性,例如:
```C
const char const_str[] = "const string";
char* str = (char*) const_str; // 错误,无法去除 const 属性
char str2[sizeof(const_str)]; // 新建一个字符数组
memcpy(str2, const_str, sizeof(const_str)); // 将 const_str 复制到 str2 中
char* result = str2; // 将字符数组转为 char*
```
c++ string 类型转为c char*
可以直接使用c_str()函数将string类型转换为c char*类型。
例如:
```c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
const char* cstr = str.c_str();
cout << cstr << endl;
return 0;
}
```
输出:
```
Hello, world!
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)