如何检查"常量 wchar_t*"是否以字符串开头?
How to check if a `const wchar_t*` starts with a string?
当我不知道字符串长度时,如何检查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")) {
// ...
}
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- C/C++预处理器是否可以检测一些编译器选项
- "非静态数据成员之前需要构造函数" - 我是否使用"boost::variant"