Pregunta

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)
¿Fue útil?

Solución

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;
}

Otros consejos

   BOOL StartsWith(BSTR sValue, BSTR prefix)
         {
         if (!prefix)
            return TRUE;
         auto prefixlen = wcslen(prefix);
         if (prefixlen == 0)
            return TRUE;
         if (!sValue)
            return FALSE;
         return wcsncmp(sValue, prefix, prefixlen) == 0;
         }

   BOOL EndsWith(BSTR sValue, BSTR suffix)
         {
         if (!suffix)
            return TRUE; // always true if suffix is blank or null
         auto suffixlen = wcslen(suffix);
         if (suffixlen == 0)
            return TRUE; // always true if suffix is blank or null
         if (!sValue)
            return FALSE;
         auto valuelen = wcslen(sValue);
         if (suffixlen > valuelen)
            return FALSE;
         auto skip = valuelen - suffixlen;
         return wcsncmp(sValue + skip, suffix, wcslen(suffix)) == 0;
         }

I've included a suffix version here and included a variation of Roman R's answer that allows for blank prefix strings.

Note: these are not well tested

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top