0

我正在使用 C++(Windows 环境)。我有一个 :

LPCWSTR mystring;

这有效:

mystring = TEXT("Hello");

但是怎么做呢?:

mystring = ((((create a new string with text = the content which is in another LPCWSTR 'myoldstring'))))

提前非常感谢!

PS:

mystring = myoldstring; 

会工作,但它不会创建一个新字符串,它将是同一个指针。我想创建一个新字符串!

4

3 回答 3

2

要使用 C++ 标准字符串,您需要包含<string>标头。由于您正在处理LPCWSTR(强调这W部分)您正在处理宽字符,因此您想使用宽字符串(即,std::wstring而不是std::string)。

#include <string>
#include <iostream>
#include <windows.h>

int main() { 
    LPCWSTR x=L"This is a string";

    std::wstring y = x;
    std::wcout << y;
}
于 2012-12-09T14:50:53.487 回答
2
LPTSTR mystring;
mystring = new TCHAR[_tcslen(oldstring) + 1];
_tcscpy(mystring, oldstring);

... After you are done ...

delete [] mystring;

这是一个完整的程序

#include <tchar.h>
#include <windows.h>
#include <string.h>

int main()
{
    LPCTSTR oldstring = _T("Hello");

    LPTSTR mystring;
    mystring = new TCHAR[_tcslen(oldstring) + 1];
    _tcscpy(mystring, oldstring);

    // Stuff

    delete [] mystring;


}

它编译得很好cl /DUNICODE /D_UNICODE a.cpp

我用过tchar宏。如果您不想使用它,那么

#include <windows.h>
#include <string.h>

int main()
{
    LPCWSTR oldstring = L"Hello";

    LPWSTR mystring;
    mystring = new WCHAR[wcslen(oldstring) + 1];
    wcscpy(mystring, oldstring);

    // Stuff

    delete [] mystring;


}

编译良好cl a.cpp

于 2012-12-09T14:55:45.643 回答
0

关于什么

string myNewString = std::string(myOldString);

只需使用字符串库的复制构造函数。

于 2012-12-09T14:33:01.323 回答