How do I check if CComBSTR starts with a specific prefix?
I come across a piece of code where I just need to do a prefix check for a given CComBSTR object (something like Y.StartsWith("X")
). C ++ is a bit foreign to me and my biggest problem is efficiency. I don't need to modify CComBSTR in any way. All I want is to return a boolean on whether it starts with an X prefix.
Looking at the operators listed in the API under CComBSTR Members , it allows very simple comparisons like ==,>, <, etc. I have two ideas on how I can try to solve this problem (see below). However, I don't have a deep understanding of what is the most efficient / easy way to do this. If I leave completely, let me know.
- Use BSRTToArray to create an array where I then iterate over the first n indices to check if it has a specific prefix.
- Get BSTR from CComBSTR and do some comparison in BSTR (haven't figured out how to do this yet).
source to share
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 suffixed version here, and included a variant of Roman R's answer that allows empty prefix strings.
Note: they are not tested well.
source to share