std::string 转 Cstring
时间: 2024-08-17 09:02:01 浏览: 61
`std::string` 是 C++ 标准库中的字符串类,而 `C-string` 通常指的是以 null 结尾的字符数组,也就是 C 语言中使用的传统字符串格式。将 `std::string` 转换为 `C-string` 可以通过多种方式实现,最直接的方式是使用 `std::string` 类提供的 `c_str()` 方法。
下面是一个使用 `c_str()` 方法将 `std::string` 转换为 `C-string` 的例子:
```cpp
#include <iostream>
#include <string>
int main() {
std::string cpp_string = "Hello World";
const char* c_string = cpp_string.c_str();
std::cout << c_string << std::endl;
return 0;
}
```
需要注意的是,`c_str()` 方法返回的是一个指向 `const char` 的指针,它指向的是 `std::string` 内部的字符数据,这个指针是有效的只要 `std::string` 对象还存在。因此,不能使用返回的指针去修改字符串的内容,除非你确保 `std::string` 对象在修改期间没有被销毁。
相关问题
std::string转CString
要将std::string转换为CString,可以使用c_str()函数。它将std::string对象转换为以null结尾的C字符串。以下是一个示例:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
const char* cstr = str.c_str();
std::cout << "std::string: " << str << std::endl;
std::cout << "CString: " << cstr << std::endl;
return 0;
}
```
在上面的示例中,我们调用std::string的c_str()函数将字符串转换为CString,并将其赋值给一个const char*变量cstr。然后,我们可以使用这个CString进行后续的操作。注意,由于c_str()返回的是指向内部缓冲区的指针,确保在使用cstr之前不要修改原始std::string对象的内容。
std::string 转cString
可以使用Unicode将std::string字符串转换为CString字符串。具体实现方法可以参考以下代码:
```
CString CMyApp::TranslatestringToCStringByUnicode(IN const string& strSource) {
CString strResult = _T("");
strResult = strSource.c_str();
return strResult;
}
```
其中,strSource为需要转换的std::string字符串,strResult为转换后的CString字符串。
另外,如果需要将CString字符串转换为std::string字符串,也可以使用以下代码实现:
```
string CMyApp::TranslateCStringTostringByUnicode(IN CString& strSource) {
int nSourceLen = strSource.GetLength();
int nSourceBytes = WideCharToMultiByte(CP_ACP, 0, strSource, nSourceLen, NULL, 0, NULL, NULL);
char* chrTemp = new char[nSourceBytes + 1];
memset(chrTemp, 0, nSourceBytes + 1);
WideCharToMultiByte(CP_OEMCP, 0, strSource, nSourceLen, chrTemp, nSourceBytes, NULL, NULL);
chrTemp[nSourceBytes] = 0;
std::string strResult = chrTemp;
delete[] chrTemp;
return strResult;
}
```