Compare first n
characters of strings
(case sensitive)
TF = strncmp(str,str,n)
TF = strncmp(str,C,n)
TF = strncmp(C,C,n)
compares
the first TF
= strncmp(str
,str
,n
)n
characters of two character vectors
for equality. The function returns a scalar logical 1 for equality,
or scalar logical 0 for inequality.
compares
the first TF
= strncmp(str
,C
,n
)n
characters of a character vector with
the first n
characters of each element of a cell
array of character vectors. The function returns a logical array the
same size as the C
input in which logical 1 represents
equality. The order of the first two input arguments is not important.
compares
each element of one cell array of character vectors with the same
element of the other. TF
= strncmp(C
,C
,n
)strncmp
attempts to match
only the first n
characters of these character
vectors. The function returns a logical array the same size as either
input array.

A character vector or mbyn character array. 

Cell array of character vectors. 

Maximum number of characters to compare. Must be a scalar, integervalued double. 

When both inputs are character arrays, When either or both inputs are a cell array of character vectors, 
Before trying the strncmp
function, use strcmp
to perform a simple comparison
of the two input character vectors. Because only the first 13 characters
are the same, strcmp
returns logical 0:
strcmp('Kansas City, KS', 'Kansas City, MO') ans = 0
Do the comparison again, but this time using strncmp
and
specifying the number of characters to compare:
chars2compare = length('Kansas City, KS')  2 ans = 13 strncmp('Kansas City, KS', 'Kansas City, MO', chars2compare) ans = 1
From a list of 10 MATLAB^{®} functions, find those that apply to using a camera:
function_list = {'calendar' 'case' 'camdolly' 'circshift' ... 'caxis' 'camtarget' 'cast' 'camorbit' ... 'callib' 'cart2sph'}; strncmp(function_list, 'cam', 3) ans = 0 0 1 0 0 1 0 1 0 0 function_list{strncmp(function_list, 'cam', 3)} ans = camdolly ans = camtarget ans = camorbit
Create two 5by10 character arrays str1
and str2
that
are equal, except for the element at row 4, column 3. Using linear
indexing, this is element 14:
str1 = ['AAAAAAAAAA'; 'BBBBBBBBBB'; 'CCCCCCCCCC'; ... 'DDDDDDDDDD'; 'EEEEEEEEEE'] str1 = AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC DDDDDDDDDD EEEEEEEEEE str2 = str1; str2(4,3) = '' str2 = AAAAAAAAAA BBBBBBBBBB CCCCCCCCCC DDDDDDDDD EEEEEEEEEE
Because MATLAB compares the arrays in linear order (that
is, column by column rather than row by row), strncmp
finds
only the first 13 elements to be the same:
str1 A B C D E A B C D E A B C D E str2 A B C D E A B C D E A B C  E  element 14 strncmp(str1, str2, 13) ans = 1 strncmp(str1, str2, 14) ans = 0