6

Is there a standard way to compare two strings in vim so that I can quickly determine which string is sorted before the other.

Something like

strcmp(str1, str2) 

to return 0 if str1 == str2, 1 if str1 > str2 and -1 if str1 < str2

8

str1 < str2 should be enough. From :h expr-<:

                use 'ignorecase'    match case     ignore case 
equal                   ==              ==#             ==?
not equal               !=              !=#             !=?
greater than            >               >#              >?
greater than or equal   >=              >=#             >=?
smaller than            <               <#              <?
smaller than or equal   <=              <=#             <=?
regexp matches          =~              =~#             =~?
regexp doesn't match    !~              !~#             !~?
same instance           is              is#             is?
different instance      isnot           isnot#          isnot?

Examples:
"abc" ==# "Abc"   evaluates to 0
"abc" ==? "Abc"   evaluates to 1
"abc" == "Abc"    evaluates to 1 if 'ignorecase' is set, 0 otherwise

...

When comparing two Strings, this is done with strcmp() or stricmp().  This
results in the mathematical difference (comparing byte values), not
necessarily the alphabetical difference in the local language.

If you want 1, 0 or -1, you can wrap this in a function:

function Strcmp(str1, str2)
    if a:str1 < a:str2
        return -1
    elseif a:str1 == a:str2
        return 0
    else
        return 1
    endif
endfunction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.