简体   繁体   English

C++ 在 std:wstring 中找到 std:string

[英]C++ find std:string in std:wstring

std::string targetDevice = "c53b1f8";
std::wstring devname;
VARIANT var;
var.vt = VT_BSTR;
pPropertyBag->Read(L"DevicePath", &var, 0);
devname = var.bstrVal;
VariantClear(&var);

if (devname.find(targetDevice) != std::string::npos) //<< my problem
{
...
}

What is the correct syntax for finding targetDevice in devname?在 devname 中查找 targetDevice 的正确语法是什么?

Problem is that different char size implies different character encoding.问题是不同的字符大小意味着不同的字符编码。 What is worse wchar_t size is platform dependent.更糟糕的是wchar_t大小取决于平台。

But assuming that you are interested in ASCII characters only and most encodings are compatible with ASCII you can use STL algorithm to do that checking:但假设您只对 ASCII 字符感兴趣并且大多数编码与 ASCII 兼容,您可以使用 STL 算法进行检查:

template <typename A, typename B>
bool contains(const A& a, const B& b)
{
     return std::search(std::begin(a), std::end(a), 
                        std::begin(b), std::end(b)) != std::end(a);
}

https://godbolt.org/z/x4bajr https://godbolt.org/z/x4bajr


you should edit your question and provide more context why you need this functionality, since I suspect there is better way to resolve your actual problem. 您应该编辑您的问题并提供更多上下文为什么您需要此功能,因为我怀疑有更好的方法来解决您的实际问题。

Since this is Windows only as pPropertyBag->Read(L"DevicePath", &var, 0);由于这是 Windows 仅作为pPropertyBag->Read(L"DevicePath", &var, 0); is a Windows Direct Show call, I decided to just make targetDevice a wstring as well.是一个 Windows Direct Show 调用,我决定将 targetDevice 也设为 wstring。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM