[英]How to replace only first occurrence of character in CString?
I have a CString st= $/Abc/cda/($/dba/abc)/
. 我有一个CString st= $/Abc/cda/($/dba/abc)/
。 I want to replace only first occurrence of $
with c:\\
. 我想只用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. 能否请你建议我只替换第一次出现的角色。
Since you are replacing a single character by three characters, you can use CString::Find()
and then CString::Delete()
and CString::Insert()
, like 由于您要用三个字符替换单个字符,您可以使用CString::Find()
然后使用CString::Delete()
和CString::Insert()
,就像
int nInx = st.Find('$');
if (nInx >= 0)
{ st.Delete(nInx, 1);
st.Insert(nInx, _T("C:\\");
}
Use 使用
find_first_of
//returns the iterator to the first occurance of string find_first_of
//将迭代器返回到第一次出现的字符串
and then 然后
replace
//to replace the iterator pointing to the first occurance replace
//以替换指向第一次出现的迭代器
You could use void SetAt( int nIndex, TCHAR ch );
你可以使用void SetAt( int nIndex, TCHAR ch );
to replace just one character. 只替换一个字符。 And then int FindOneOf( LPCTSTR lpszCharSet ) const;
然后是int FindOneOf( LPCTSTR lpszCharSet ) const;
to find the first occurance of $. 找到$的第一次出现。
Like this : 像这样 :
st.SetAt( st.FindOneOf( "$" ), "C:/");
Here is a function that encapsulates the accepted answer from Edward Clements: 这是一个函数,它包含了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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.