Matlab string comparison (realize the function similar to strcmp in C language)

I encountered a problem today. I wanted to use Matlab to compare the size of two strings. I thought it was enough >、<、==. Who knows that these comparison symbols return a logical matrix (and generally require that the two strings have the same length). I searched on the Internet. Just say add all()、any(). Indeed, all means [all of them], and any means [only one], but you can’t judge who is bigger and who is smaller. The strcmp that comes with matlab can only judge whether two strings are equal (equal is true, otherwise Is false), and can’t judge who is big and who is small. I accidentally found that a predecessor wrote a function. The function of this function is similar to strcmp in C language:

  • str1<str2, return 1
  • str1==str2, return 0
  • str1<str2, return -1

Do some excerpts to prevent entering the pit again next time, the function is as follows:

function p=mstrcmp(str1,str2)
k=min(length(str1),length(str2));
for n=1:k   %Compare the top k
    if(str1(n)>str2(n))
        p=1;break;
    elseif(str1(n)==str2(n))
        p=0;
    else p=-1;break;
    end
end
if(p==0)
    if(length(str1)>length(str2)) %The first k bits are equal, but str1 is longer
        p=1;
    elseif(length(str1)==length(str2))
        p=0;
    else p=-1;
    end
end
end

Guess you like

Origin blog.csdn.net/Gou_Hailong/article/details/114753221