将string转换为char[]
时间: 2023-05-31 21:05:55 浏览: 52
可以直接使用toCharArray()方法将string转换为char[],例如:
``` java
String str = "hello";
char[] charArray = str.toCharArray();
```
这样就可以将字符串"hello"转换为一个包含每个字符的char数组了。
相关问题
C++将string转化为char
将string转换为char数组可以通过调用string对象的c_str()方法来实现。例如:
```cpp
string str = "hello world";
const char *cstr = str.c_str(); // 将string转化为const char *
char char_array[str.size() + 1]; // 定义一个char数组
strcpy(char_array, cstr); // 将cstr中的字符复制到char_array中
```
请注意,使用c_str()方法返回的char指针指向的是一个const char类型的字符串,因此如果要将其存储到char数组中,需要使用strcpy()等函数进行复制。同时,由于char数组中需要存储字符串结束符'\0',因此数组大小应该是string长度加1。
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;
}
```
相关推荐
![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)