MATLAB Answers

How do I get MATLAB to compare strings in the same way as the strcmp(str1,str2) method in the ANSI C API?

20 views (last 30 days)
I would like to perform string comparisons between strings that possibly have differing lengths that is consistent with the C API call of the STRCMP method in C with this signature:
int strcmp ( const char * str1, const char * str2 );
I expect the function to perform as follows:
Return 0 if the strings are identical
Return 1 if the ASCII value of the first non-matching character of string 1 is greater than string 2.
Return -1 if the ASCII value of the first non-matching character of string 1 is less than string 2.
strcmp('ibm','ibn')
strcmp('orcl','ibm')
should return '-1' and '1' respectively.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 17 Feb 2021
Edited: MathWorks Support Team on 17 Feb 2021
STRCMP in MATLAB performs a character-wise comparison of strings, but does not provide more information regarding the match.
To work around this issue, there are useful third-party submissions at the MathWorks File Exchange that perform string-comparison in the same way as the C API. These files can be downloaded at the following location and saved to a MATLAB path directory:
Note that MathWorks does not guarantee or warrant the use or content of these submissions. Any questions, issues, or complaints should be directed to the contributing author.

More Answers (1)

Shlomo Geva
Shlomo Geva on 23 Feb 2021
Edited: Shlomo Geva on 25 Feb 2021
function c = cstrcmp(a,b)
% c style strcmp. No type checks, use only strings and char arrays.
if strcmp(a,b)
c=0;
else
[idx,idx]=sort({char(a),char(b)});
c=idx(1)-idx(2);
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by