Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have a string saved as LPWSTR.
I have to make a change in this string (reduce some characters) and save it as LPCWSTR.
How can i do it?

Thanks
Posted

1 solution

You don't need any conversion from non-constant to constant string. Apparently, they are compatible in the assignment direction you want. Let's see:

C++
#include <windows.h>

//...

LPWSTR variable = L"my string";
variable[0] = 'M';
LPCWSTR constString = variable;


If you need to do the opposite, type cast is needed, because it would break the assumption on the string data being immutable. There are two ways:

C++
LPWSTR newString = (LPWSTR)constString;
LPWSTR newString2 = const_cast<LPWSTR>(constString);


—SA
 
Share this answer
 
v4
Comments
Espen Harlinn 30-Mar-11 15:42pm    
Good points, 5ed!
Sergey Alexandrovich Kryukov 30-Mar-11 17:04pm    
Thank you, Espen. I guess that's all what involved.
--SA
Guyverthree 31-Mar-11 5:33am    
Indeed they are the same for assignment purposes.
polaringu 3-Jun-11 5:16am    
LPWSTR variable = L"my string";
variable[0] = 'M';

You can't do that, because you're changing the constant memory which is forbidden.
To do that you'll need to add a buffer, like so:
WCHAR buf[256] = L"my string"; //can be dynamic
LPWSTR variable = buf;
variable[0] = 'M';

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900