Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 410
user2499879 Avatar asked Jun 19 '13 06:06

user2499879


People also ask

How do you replace first occurrence?

Use the replace() method to replace the first occurrence of a character in a string. The method takes a regular expression and a replacement string as parameters and returns a new string with one or more matches replaced.

How do I change the first occurrence of a character in a string?

To replace the first occurrence of a character in Java, use the replaceFirst() method. Here is our string. str.

How do I change the first occurrence of a character in python?

replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.


Video Answer


2 Answers

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:\\");
}
like image 200
Edward Clements Avatar answered Sep 19 '22 11:09

Edward Clements


Use

find_first_of //returns the iterator to the first occurance of string

and then

replace //to replace the iterator pointing to the first occurance

like image 22
Jayram Avatar answered Sep 20 '22 11:09

Jayram