C++里将char *转化为string
时间: 2023-08-14 18:07:23 浏览: 200
可以使用`std::string`的构造函数将`char*`类型转换为`std::string`类型。例如:
```c++
char* cstr = "Hello, World!";
std::string str = std::string(cstr);
```
或者可以使用`std::string`的赋值操作符,例如:
```c++
char* cstr = "Hello, World!";
std::string str;
str = cstr;
```
需要注意的是,如果`char*`指向的字符串中包含`\0`字符,那么在转换为`std::string`时会将其作为字符串的结尾,因此可能会截断字符串。如果想要避免这种情况,可以使用`std::string`的另一个构造函数,该构造函数需要指定字符串的长度,例如:
```c++
char cstr[] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'};
std::string str(cstr, sizeof(cstr));
```
相关问题
C++如何将char*转换为string?
可以使用string类的构造函数将char*转换为string,例如:
```c++
char* cstr = "hello";
string str(cstr);
```
或者使用string类的assign函数将char*赋值给string,例如:
```c++
char* cstr = "hello";
string str;
str.assign(cstr);
```
C++将char*数组转换为string
可以使用string的构造函数来将char*数组转换为string,示例如下:
```c++
char arr[] = "Hello, World!";
string str(arr);
```
这里使用了string的构造函数,将char*数组作为参数传入,构造出一个string对象。注意,如果char*数组中包含了空字符'\0',那么转换后的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)