How to use random_shuffle with CString?

180 views Asked by At

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?

2

There are 2 answers

5
user4815162342 On BEST ANSWER

Use GetBuffer to obtain the character buffer, and pass its boundaries to std::random_shuffle:

void shuffle_cstring(CString& c)
{
    size_t len = c.GetLength();
    LPTSTR buf = c.GetBuffer(1);
    std::random_shuffle(buf, buf + len);
    c.ReleaseBuffer();
}
1
ravi 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());