Irakli Lekishvili
Irakli Lekishvili

Reputation: 34158

check if WCHAR contains string

I have variable WCHAR sDisplayName[1024];

How can I check if sDisplayName contains the string "example"?

Upvotes: 11

Views: 17990

Answers (3)

Seva Alekseyev
Seva Alekseyev

Reputation: 61378

if(wcscmp(sDisplayName, L"example") == 0)
    ; //then it contains "example"
else
    ; //it does not

This does not cover the case where the string in sDisplayName starts with "example" or has "example" in the middle. For those cases, you can use wcsncmp and wcsstr.

Also this check is case sensitive.

Also this will break if sDisplayName contains garbage - i. e. is not null terminated.

Consider using std::wstring instead. That's the C++ way.

EDIT: if you want to match the beginning of the string:

if(wcsncmp(sDisplayName, L"Adobe", 5) == 0)
    //Starts with "Adobe"

If you want to find the string in the middle

if(wcsstr(sDisplayName, L"Adobe") != 0)
    //Contains "Adobe"

Note that wcsstr returns nonzero if the string is found, unlike the rest.

Upvotes: 18

cppguy
cppguy

Reputation: 3713

wscstr will find your string anywhere in sDisplayName, wsccmp will see if sDisplayName is exactly your string.

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124692

You can use the wchar_t variants of standard C functions (i.e., wcsstr).

Upvotes: 1

Related Questions