string 转char
时间: 2023-07-20 13:08:15 浏览: 44
可以通过以下方式将 string 转换为 char*:
```cpp
#include <iostream>
#include <cstring>
int main() {
std::string s = "hello world";
char* cstr = new char[s.length() + 1];
std::strcpy(cstr, s.c_str());
std::cout << cstr << std::endl;
delete[] cstr;
return 0;
}
```
在这个例子中,我们首先创建了一个 std::string 对象 s。然后,我们使用 new 运算符创建了一个 char* 数组 cstr,其大小为 s.length() + 1(因为字符串以 null 结尾)。接下来,我们使用 std::strcpy 函数将 s 中的内容复制到 cstr 中。最后,我们输出 cstr 并删除它。
相关问题
string转char
我明白了,你想知道如何将string转换为char数组。可以使用string的c_str()方法将其转换为const char指针,然后再使用strcpy()或memcpy()函数将其拷贝到char数组中。以下是示例代码:
```
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string str = "hello, world!";
char str_char[str.size() + 1];
strcpy(str_char, str.c_str());
cout << "string转换为char数组结果为:" << str_char << endl;
return 0;
}
```
请注意,在分配char数组时需多分配一个字符空间存储字符串结束符'\0'。
String 转char
要将一个字符串(String)转换为字符数组(char[]),可以使用String类的toCharArray()方法。这个方法将返回一个新的字符数组,其中包含字符串中的每个字符。
下面是一个示例代码:
```java
String str = "Hello";
char[] charArray = str.toCharArray();
// 打印字符数组
for (char c : charArray) {
System.out.print(c + " ");
}
```
输出结果为:H e l l o
这样就将字符串"Hello"转换为了字符数组charArray。你可以根据需要进一步处理字符数组中的每个字符。
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)