Link to home
Start Free TrialLog in
Avatar of mnopix
mnopix

asked on

CComBSTRr find replace

Hi,

I've a CComBSTR variable as below:
CComBSTR bstrUrl= L"https://www.experts-exchange.com/";

Here, how to change the  "https" into "http"  in the above string. No MFC involved so CString cannot be used.

Thanks in advance


Avatar of mrwad99
mrwad99
Flag of United Kingdom of Great Britain and Northern Ireland image

The underlying storage for a CComBSTR is the public member CComBSTR::m_str, which is a BSTR.  Now, a BSTR is typdef'ed as OLECHAR *BSTR, and an OLECHAR* is typdef'ed as a WCHAR.  A WCHAR is a wchar_t, so it follows then that all a CComBSTR is is a wrapper around a wchar_t*.

Internally, the constructor has the code

m_str = ::SysAllocString(pSrc);

where pSrc is the string you passed in.  The destructor, I would assume, calls SysFreeString, passing m_str.  (I cannot prove this since I cannot step into the destructor for some reason).  

Anyway, that being said, you can see that you can use standard wide string handling API functions to manipulate the member m_str, or, as I did, std::wstring, which is a lot easier.  The only thing you need to watch out for is that you take care of the memory occupied by m_str, if, for example, you increase the length of it.  You could write a wrapper function to do a replace operation, something like the code below.

HTH
      
void ReplaceInCComBSTR ( CComBSTR& strInput, const std::wstring& strOld, const std::wstring& strNew )
{
     std::wstring strOutput (  strInput );
     int pos = 0;
     int lpos = 0;
     while ( ( pos = strOutput.find ( strOld, lpos ) ) != string::npos )
     {
           strOutput.replace ( pos, strOld.length(), strNew );
           lpos = pos+1;
     }
 
	 // Find and replace is complete; now update the CComBSTR!
	 ::SysFreeString ( strInput.m_str );
	 strInput.m_str = ::SysAllocString ( strOutput.c_str() );
}
 
// ...
 
	CComBSTR bstrUrl=  L"https://www.experts-exchange.com/";
 
	ReplaceInCComBSTR ( bstrUrl, L"https:", L"http:" );

Open in new window

>> and an OLECHAR* is typdef'ed as a WCHAR

should be

and an OLECHAR is typdef'ed as a WCHAR (no pointer type)
Avatar of mnopix
mnopix

ASKER

I'm getting following compile errors:
abc.cpp(1716) : error C2653: 'string' : is not a class or namespace name
abc.cpp(1716) : errorC2065: 'npos' : undeclared identifier

Am I missing some include files?
Avatar of mnopix

ASKER

About the Build Environment:
Windows Server 2003
Platform Builder for MS Windows CE 5.0
ASKER CERTIFIED SOLUTION
Avatar of mrwad99
mrwad99
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mnopix

ASKER

Thank you very much for your effort. As our project approch was changed we decided keep the 'https' as its.  So I've not verified the last comment.
No problem, you will find it works :)