Search code examples
c++visual-c++stlmfc

How to replace only first occurrence of character in CString?


I have a CString st= $/Abc/cda/($/dba/abc)/. I want to replace only first occurrence of $ with c:\.

I have tried to replace as

st.Replace("$","c:\");

But it replaced all occurrence of $.

Could you please suggest me any logic to only replace the first occurrence of character.


Solution

  • Since you are replacing a single character by three characters, you can use CString::Find() and then CString::Delete() and CString::Insert(), like

    int nInx = st.Find('$');
    if (nInx >= 0)
    {    st.Delete(nInx, 1);
         st.Insert(nInx, _T("C:\\");
    }