{
UINT i, nCount=0;
BOOL bFind;
LPCTSTR ps, pf;
LPTSTR buf=NULL, pt = target;
size_t nLenSrc = _tcslen( source );
buf = new TCHAR[nLenSrc+1];
if ( buf == NULL )
return NULL;
_tcsncpy( buf, source, nLenSrc );
buf[nLenSrc] = 0;
for(ps=buf; *ps; ps++)
{
if ( find[0] == *ps )
{
bFind = TRUE;
for(pf=find+1, i=1; *pf; pf++, i++)
{
if ( *pf != ps[i] )
{
bFind = FALSE;
break;
}
}
// 찾았다!
if ( bFind )
{
for(pf=replace; *pf; pf++)
*(pt++) = *pf;
ps += (--i);
nCount++;
continue;
}
}
*(pt++) = *ps;
}
*pt = 0;
delete[] buf;
return nCount;
}
다른 점은 _tcsncmp와 _tcscpy 함수를 썼다는 것입니다.
아주 미세한 차이지만 함수를 쓰는것보다
직접 포인터 연산한 이전 버전의 속도가 더 잘 나오네요.
하지만, 가독성 면에서 이번 코드가 더 좋습니다.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
UINT Replace( LPTSTR target, LPCTSTR source, LPCTSTR find, LPCTSTR replace )
{
UINT nCount = 0;
LPCTSTR ps;
LPTSTR buf=NULL, pt = target;
size_t nLenSrc = _tcslen( source );
size_t nLenFind = _tcslen( find );
size_t nLenRepl = _tcslen( replace );
buf = new TCHAR[nLenSrc+1];
if ( buf == NULL )
return NULL;
_tcsncpy( buf, source, nLenSrc );
buf[nLenSrc] = 0;
for(ps=buf; *ps; ps++)
{
if ( _tcsncmp( find, ps, nLenFind ) == 0 )
{
_tcsncpy( pt, replace, nLenRepl );
ps += (nLenFind-1);
pt += nLenRepl;
nCount++;
continue;
}
*(pt++) = *ps;
}
*pt = 0;
delete[] buf;
return nCount;
}