如何检查"常量 wchar_t*"是否以字符串开头?

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

本文关键字:quot 是否 开头 字符串 常量 何检查 检查 wchar      更新时间:2024-09-30

当我不知道字符串长度时,如何检查LPCWSTR(const wchar_t*)是否以字符串开头?

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

您可以使用wcsncmp(https://cplusplus.com/reference/cwchar/wcsncmp/):

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

请注意,第三个参数表示要比较的字符数。所以它应该等于要找到的长度。

编辑:要知道要查找的字符串的长度,您可以使用wcslen

auto length = wcslen(stringToFind);

这两个函数都来自#include <cwchar>

如果您不介意(潜在的)额外分配并可以访问 C++20 编译器,您可以使用starts_with(我们只花了 40 年的时间就到了这里......

#include <string>
LPCWSTR str = L"abc def";
if (std::wstring(str).starts_with(L"abc")) {
}

您可以使用在 C++20 中也接受starts_with处理的string_view来保存分配。这更便宜,但仍然具有至少遍历一次输入序列以计算长度的开销(string_view要求):

#include <string_view>
LPCWSTR str = L"abc def";
if (std::wstring_view(str).starts_with(L"abc")) {
}

计算上最便宜的选择是std::wcsncmp,尽管它需要更多的信息重复:

#include <cwchar>
LPCWSTR str = L"abc def";
if (std::wcsncmp(str, L"abc", 3) == 0) {
}

值得庆幸的是,我们有模板,所以我们不必重复自己(并引入一个让数据不同步的机会):

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