1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
////////////////////////////////////////////////////////////////////////////////
bool CMyString::Replace(LPCWSTR pszOldStr, LPCWSTR pszNewStr)
{
TRACE_FUNC("Entering CMyString::Replace");
if (!ISVALIDSTRING(pszOldStr) || !ISVALIDSTRING(pszNewStr) || GetLength() == 0)
{
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
LPCWSTR pszString = NULL;
LPCWSTR pszTemp = CMyString::m_StrBuff.Ptr();
LPWSTR pszResult = NULL;
DWORD dwFound = 0;
DWORD dwOldLen = (DWORD)wcslen(pszOldStr);
DWORD dwNewLen = (DWORD)wcslen(pszNewStr);
DWORD dwLen, dwResLen;
while (NULL != (pszTemp=wcsstr(pszTemp, pszOldStr)))
++dwFound, pszTemp+=dwOldLen;
dwLen = ((DWORD)wcslen(m_StrBuff.Ptr()))+dwFound*(dwNewLen-dwOldLen);
if (NULL == (pszResult=(LPWSTR)malloc((sizeof(wchar_t))*(dwLen+1))))
{
return false; // not enough memory
}
else
{
pszTemp=m_StrBuff.Ptr();
dwResLen=0; // length of result
// replace old strings with new strings
while (NULL != (pszTemp=wcsstr(pszTemp, pszOldStr)))
{
dwLen=(pszTemp-m_StrBuff.Ptr()); // number of chars to keep
//wcsncpy(pszResult+dwResLen, m_StrBuff.Ptr(), dwLen);
wcsncpy_s(pszResult+dwResLen, wcslen(pszResult), m_StrBuff.Ptr(), dwLen); // original part
//wcscpy(pszResult+(dwResLen+=dwLen), pszNewStr);cmd
wcscpy_s(pszResult+(dwResLen+=dwLen), wcslen(pszResult), pszNewStr); // insert new
dwResLen+=dwNewLen;
pszTemp+=dwOldLen;
pszString=pszTemp;
}
//wcscpy(pszResult+dwResLen, pszString);
wcscpy_s(pszResult+dwResLen, wcslen(pszResult), pszString); // copy last part
CreateCopy(pszResult); // writes content from pszResult in m_StrBuff
}
return true;
}
|