I would like to shuffle the characters present in CString varible. How do i do it? Std provide a finction called random_shuffle() which can be used to shuffle std::string in the following way std::string s("ThisIsSample"); random_shuffle(s.first(),s.last()); But since CString doesnt have a function to access the fisrt and last character to iterate. How do i use random_shuffle with CString?
How to use random_shuffle with CString?
180 views Asked by user2543264 At
2
There are 2 answers
1
On
Convert CString to std::string:-
CString cs("Hello");
std::string s((LPCTSTR)cs);
NOTE:- BUT: std::string cannot always construct from a LPCTSTR. i.e. the code
will fail for UNICODE builds.
EDIT IN RESPONSE TO COMMENT
As std::string can construct only from LPSTR / LPCSTR, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA as an intermediary.
CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
Use random_shuffle on s and then:-
CString cs1(s.c_str());
Use
GetBuffer
to obtain the character buffer, and pass its boundaries tostd::random_shuffle
: