请问大家C++里面有没有字符串替换函数?  类似于VB里面的Stringreplace如果没有 应该怎么样写一个?不能用MFC的cstring类,大家帮帮忙  100分送了

解决方案 »

  1.   

    CString类实际上也是调用基本的字符串和内存操作int CString::Replace(LPCTSTR lpszOld, LPCTSTR lpszNew)
    {
    // can't have empty or NULL lpszOld int nSourceLen = SafeStrlen(lpszOld);
    if (nSourceLen == 0)
    return 0;
    int nReplacementLen = SafeStrlen(lpszNew); // loop once to figure out the size of the result string
    int nCount = 0;
    LPTSTR lpszStart = m_pchData;
    LPTSTR lpszEnd = m_pchData + GetData()->nDataLength;
    LPTSTR lpszTarget;
    while (lpszStart < lpszEnd)
    {
    while ((lpszTarget = _tcsstr(lpszStart, lpszOld)) != NULL)
    {
    nCount++;
    lpszStart = lpszTarget + nSourceLen;
    }
    lpszStart += lstrlen(lpszStart) + 1;
    } // if any changes were made, make them
    if (nCount > 0)
    {
    CopyBeforeWrite(); // if the buffer is too small, just
    //   allocate a new buffer (slow but sure)
    int nOldLength = GetData()->nDataLength;
    int nNewLength =  nOldLength + (nReplacementLen-nSourceLen)*nCount;
    if (GetData()->nAllocLength < nNewLength || GetData()->nRefs > 1)
    {
    CStringData* pOldData = GetData();
    LPTSTR pstr = m_pchData;
    AllocBuffer(nNewLength);
    memcpy(m_pchData, pstr, pOldData->nDataLength*sizeof(TCHAR));
    CString::Release(pOldData);
    }
    // else, we just do it in-place
    lpszStart = m_pchData;
    lpszEnd = m_pchData + GetData()->nDataLength; // loop again to actually do the work
    while (lpszStart < lpszEnd)
    {
    while ( (lpszTarget = _tcsstr(lpszStart, lpszOld)) != NULL)
    {
    int nBalance = nOldLength - (lpszTarget - m_pchData + nSourceLen);
    memmove(lpszTarget + nReplacementLen, lpszTarget + nSourceLen,
    nBalance * sizeof(TCHAR));
    memcpy(lpszTarget, lpszNew, nReplacementLen*sizeof(TCHAR));
    lpszStart = lpszTarget + nReplacementLen;
    lpszStart[nBalance] = '\0';
    nOldLength += (nReplacementLen - nSourceLen);
    }
    lpszStart += lstrlen(lpszStart) + 1;
    }
    ASSERT(m_pchData[nNewLength] == '\0');
    GetData()->nDataLength = nNewLength;
    } return nCount;
    }
      

  2.   

    有没有只通过char数组来替换的函数啊?????/我需要的是char实现的
      

  3.   

    不能用STL的string吗?反正你都是C++了?
      

  4.   

    c++的标准库是没有的
    但是STL的库里我记得好象有函数
    好久不用了 要去查查
      

  5.   

    该说的楼上诸位都说了……
    总之针对于char型数组,可以按地址、下标逐一判断操作
    string的话,不用我多说啦