Ahmed T. Yousef
Ahmed T. Yousef

Reputation: 73

string.find() returns true wrongfully

Well the code explains what i am trying to do

auto haystack = wstring(L"\REGISTRY\MACHINE\SOFTWARE\WOW6432Node\Data\0\Path");
auto needle = wstring(L"\WOW6432Node\Data\0\Name");
auto found = haystack.find(needle) != haystack.npos;
cout << found << endl;

it returns true although needle is different than haystack notice the former ends with \Path while the latter ends with \Name... how could i exactly tell if certain string contains another ?

Upvotes: 2

Views: 112

Answers (3)

user2249683
user2249683

Reputation:

Due to the terminating '\0' the strings are shorter than you think:

auto haystack = std::wstring(L"\REGISTRY\MACHINE\SOFTWARE\WOW6432Node\Data");
auto needle = std::wstring(L"\WOW6432Node\Data");

The other unintended escape sequences should produce a compiler warning:

g++: warning: unknown escape sequence: '\R' (... and more)

You may look into: http://en.cppreference.com/w/cpp/language/string_literal

Upvotes: 2

Logman
Logman

Reputation: 4189

You can do it like this:

wstring haystack = wstring(LR"P(\REGISTRY\MACHINE\SOFTWARE\WOW6432Node\Data\0\Path)P");
wstring needle = wstring(LR"P(\WOW6432Node\Data\0\Name)P");
bool found = haystack.find(needle) != haystack.npos;
cout << (char*)(found?"True":"False") << endl;

\0 is a problem for you as it end constructor prematurely

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76414

The \ character is the escape character. To use the actual \ character you need to escape it with \\. So your code needs to be changed like this:

auto haystack = wstring(L"\\REGISTRY\\MACHINE\\SOFTWARE\\WOW6432Node\\Data\\0\\Path");
auto needle = wstring(L"\\WOW6432Node\\Data\\0\\Name");
auto found = haystack.find(needle) != haystack.npos;
cout << found << endl;

Upvotes: 0

Related Questions