Search code examples
c++windowsstringvisual-c++bstr

How to check if a _bstr_t contains (similar to str.find) a string


I am new to _bstr_t's and still trying to get the hang of it. I was trying to check whether a particular string x is contained anywhere within the bstring. Something I would normally do like;

String x = "hello";
String example = "You! hello there";
...
if (example.find(x) != string::npos) {
...

Just for the record the intended platform is windows.


Solution

  • There is no need to use _bstr_t. Use the BSTR type.

    Next, read Eric's Complete Guide to BSTR Semantics.

    Lastly, you can use the BSTR in native code the way you would a normal character array in most cases.

    BSTR bstr = SysAllocString(L"FooBarBazQux");
    if (wcsstr(bstr, L"Bar") != NULL) {
      // Found it! Do something.
    } else {
      // Not there.
    }
    SysFreeString(bstr);
    

    MSDN for wcsstr.