Cesar
Cesar

Reputation: 389

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

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) {
}

Upvotes: 1

Views: 664

Answers (2)

IInspectable
IInspectable

Reputation: 51413

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")) {
}

You can save the allocation by using a string_view that also received the starts_with treatment in C++20. This is less expensive but still has the overhead of walking the input sequence at least once to calculate the length (required by the string_view):

#include <string_view>

LPCWSTR str = L"abc def";

if (std::wstring_view(str).starts_with(L"abc")) {
}

The computationally cheapest option would be std::wcsncmp, though it requires a bit more repetition of information:

#include <cwchar>

LPCWSTR str = L"abc def";

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

Thankfully, we have templates, so we don't have to repeat ourselves (and introduce an opportunity to let data run out of sync):

#include <cwchar>

template<size_t N>
[[nodiscard]]
constexpr bool starts_with(wchar_t const* str, wchar_t const (&cmp)[N]) noexcept {
    return std::wcsncmp(str, cmp, N - 1) == 0;
}

// ...

LPCWSTR str = L"abc def";

if (starts_with(str, L"abc")) {
    // ...
}

Upvotes: 1

Iv&#225;n
Iv&#225;n

Reputation: 1060

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>

Upvotes: 1

Related Questions