String Compare- different result

Mingyang Du 20 Reputation points
2023-07-20T09:15:05.2166667+00:00

Hi there,

std::wcscmp StrCmp VarBstrCmp returns different result when compare "~" and "a"

std::wcscmp returns 1

StrCmp and VarBstrCmp return -1. Look like they don't follow the ascii-code order. Does anybody know the reason?

Below is the sample code.

Thanks in advance,

Mingyang


#include <cstring>
#include <iostream>
#include <windows.h>
#include <objbase.h>
#include <oleauto.h>
#include <Shlwapi.h>

int main()
{
   
    int c = -100;
    wchar_t * sw1 = L"~";
    wchar_t * sw2 = L"a";
    c = std::wcscmp(sw1, sw2);
    c = -100;

    c = StrCmp(sw1, sw2);
    c = -100;

    LCID lcid = 0x0009;
    HRESULT hCmp = VarBstrCmp(sw1, sw2, lcid, 0);
    if (hCmp == VARCMP_GT)
        c = 1;
    else if (hCmp == VARCMP_LT)
        c = -1;
    else
        c = 0;
}

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,850 questions
{count} votes

Accepted answer
  1. RLWA32 47,021 Reputation points
    2023-07-25T07:34:31.9633333+00:00

    Functions like StrCmpW and VarBstrCmp do a lot more work internally to deal with locales and sorting than the wcscmp CRT function. For example, after getting sorting information StrCmpW internally calls kernel32.dll!SortCompareString(void).

    The documentation at Handling Sorting in Your Applications states "The functions CompareString, CompareStringEx, lstrcmp, lstrcmpi, LCMapString, LCMapStringEx, FindNLSString, and FindNLSStringEx all default to use of a "word sort" technique. For this type of sort, all punctuation marks and other nonalphanumeric characters, except for the hyphen and the apostrophe, come before any alphanumeric character." The '~' character is nonalphanumeric and in my opinion that is the reason for the difference in the comparison results.

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.