| Programming and Data Types | ![]() |
Comparing Strings For Equality
There are four functions that determine if two input strings are identical:
strcmp determines if two strings are identical.strncmp determines if the first n characters of two strings are identical.strcmpi and strncmpi are the same as strcmp and strncmp, except that they ignore case.str1 = 'hello'; str2 = 'help';
Strings str1 and str2 are not identical, so invoking strcmp returns 0 (false). For example,
C = strcmp(str1,str2)
C =
0
Note
For C programmers, this is an important difference between MATLAB's
strcmp and C's strcmp(), which returns 0 if the two strings are the same.
|
The first three characters of str1 and str2 are identical, so invoking strncmp with any value up to 3 returns 1.
C = strncmp(str1,str2,2)
C =
1
These functions work cell-by-cell on a cell array of strings. Consider the two cell arrays of strings
A = {'pizza';'chips';'candy'};
B = {'pizza';'chocolate';'pretzels'};
Now apply the string comparison functions.
strcmp(A,B)
ans =
1
0
0
strncmp(A,B,1)
ans =
1
1
0
| String Comparisons | Comparing for Equality Using Operators | ![]() |