user2499879
user2499879

Reputation: 693

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.

Upvotes: 7

Views: 7762

Answers (3)

olevegard
olevegard

Reputation: 5532

If you only need to replace a character with another character, you could use SetAt in conjunction with FindFirstOf. FindFirstOf will find the index of the first occurrence of the character you want to replace. By passing that as the first argument of SetAt, and the replacement character as the second argument, you can replace the first "$" with, say, "#":

st.SetAt( st.FindOneOf( "$" ), "#");

This doesn't work for the specific case mentioned in the question, though, where you need to replace the "$" character with a multi-character string. For that, you'll need to use Edward Clements's solution.

Upvotes: 0

Scott Hutchinson
Scott Hutchinson

Reputation: 1721

Here is a function that encapsulates the accepted answer from Edward Clements:

int replaceFirstOf(CString& str, const LPCSTR pszOld, const LPCSTR pszNew)
{
    int found = str.Find(pszOld);
    if (found >= 0)
    {
        str.Delete(found, 1);
        str.Insert(found, pszNew);
    }   
    return found;
}

Upvotes: 0

Edward Clements
Edward Clements

Reputation: 5132

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:\\");
}

Upvotes: 5

Related Questions