string 转 char
时间: 2023-07-20 11:07:43 浏览: 46
将 C++ 的 std::string 转换为 C 风格的 char*,可以使用 std::string 的成员函数 c_str(),它返回一个指向以 null 结尾的字符数组的指针,即 C 风格的字符串。
示例代码:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
const char* c_str = str.c_str();
std::cout << "std::string: " << str << std::endl;
std::cout << "C-style string: " << c_str << std::endl;
return 0;
}
```
输出:
```
std::string: Hello, world!
C-style string: Hello, world!
```
相关问题
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*:
```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 并删除它。