Home > Blockchain >  How to check if a `const wchar_t*` starts with a string?
How to check if a `const wchar_t*` starts with a string?

Time:08-15

How can I check if an LPCWSTR (const wchar_t*) starts with a string when I don't know the string length?

LPCWSTR str = L"abc def";

if (?(str, L"abc") == 0) {
}

CodePudding user response:

You can use wcsncmp (https://cplusplus.com/reference/cwchar/wcsncmp/):

LPCWSTR str = L"abc def";

if (wcsncmp(str, L"abc", 3) == 0) {
}

Note that the third parameter means how many characters you want to compare. So it should equal the length of the tring to find.

Edit: To know the length of the string to find, you can use wcslen:

auto length = wcslen(stringToFind);

Both functions come from #include <cwchar>

CodePudding user response:

If you don't mind the (potential) extra allocation and have access to a C 20 compiler, you can use starts_with (it's only taken us 40 years to get here...):

#include <string>

LPCWSTR str = L"abc def";

if (std::wstring(str).starts_with(L"abc")) {
}
  • Related