I used this function in my work. I wanted to find it on the Internet and did not find it. I wrote it myself.
// Lpsrc ---- [In, out] DEST string, after replacing string, it will contain result string
// Lpoldstr ---- string which will be replaced
// Lpnewstr ---- new string for replacing
Void replacestring (lptstr & lpsrc, lptstr lpoldstr, lptstr lpnewstr)
{
If (! Lpsrc |! Lpoldstr |! Lpnewstr)
Return;
Int noldlen = strlen (lpoldstr );
Int nnewlen = strlen (lpnewstr );
Int ncount = 0;
Lptstr lpszstart = lpsrc;
Lptstr lpszend = lpsrc + strlen (lpsrc );
Lptstr lpsztarget;
Lptstr lptempsrc;
While (lpszstart <lpszend)
{
While (lpsztarget = strstr (lpszstart, lpoldstr ))! = NULL)
{
Ncount ++;
Lpszstart = lpsztarget + noldlen;
}
Lpszstart + = strlen (lpszstart) + 1;
}
If (ncount> 0)
{
Int noldsrclen = strlen (lpsrc) + 1;
Int nnewsrclen = noldsrclen + (nnewlen-noldlen) * ncount;
If (nnewsrclen> noldsrclen)
{
Lptempsrc = new tchar [noldsrclen];
If (lptempsrc)
{
Memset (lptempsrc, 0, noldsrclen );
Memcpy (lptempsrc, lpsrc, noldsrclen );
Delete [] lpsrc;
Lpsrc = new tchar [nnewsrclen];
If (lpsrc)
{
Memset (lpsrc, 0, nnewsrclen );
Memcpy (lpsrc, lptempsrc, noldsrclen );
}
Delete [] lptempsrc;
Lptempsrc = NULL;
}
}
Lpszstart = lpsrc;
Lpszend = lpsrc + strlen (lpsrc );
While (lpszstart <lpszend)
{
While (lpsztarget = strstr (lpszstart, lpoldstr ))! = NULL)
{
Int nbalance = noldsrclen-(lpsztarget-lpsrc + noldlen );
Memmove (lpsztarget + nnewlen, lpsztarget + noldlen, nbalance * sizeof (tchar ));
Memcpy (lpsztarget, lpnewstr, nnewlen * sizeof (tchar ));
Lpszstart = lpsztarget + nnewlen;
Noldsrclen + = (nnewlen-noldlen );
}
Lpszstart + = strlen (lpszstart) + 1;
}
}
}