Search code examples
stringvisual-c++atlbstr

How to check if a CComBSTR starts with a certain prefix?


I'm encountering a piece of code where I need to simply do a prefix check on a given CComBSTR object (something like Y.StartsWith("X")). C++ is a bit foreign to me, and my biggest concern is efficiency. I don't need to modify the CComBSTR in any way. All I want is to return a boolean on whether it starts with X prefix.

Looking at the operators listed in the API under CComBSTR Members, it allows for very basic comparisons like ==, >, <, etc. I have two ideas on how I could try to solve this (listed below). However, I don't have a deep understanding of what is the most efficient/simplest way to go about this. If I'm completely off base, let me know.

  1. Use BSRTToArray to create an array where I then iterate over the first n indices to check if a it has a certain prefix.
  2. Get the BSTR from the CComBSTR and do some comparison on the BSTR (haven't worked out how to do this yet)

Solution

  • wcsncmp will compare a limited number of starting characters for you:

    BOOL StartsWith(BSTR sValue, const WCHAR* pszSubValue)
    {
        if(!sValue)
            return FALSE;
        return wcsncmp(sValue, pszSubValue, wcslen(pszSubValue)) == 0;
    }