Documentation |
Compare first n characters of strings (case sensitive)
TF = strncmp(string,string,n)
TF = strncmp(string,cellstr,n)
TF = strncmp(cellstr,cellstr,n)
TF = strncmp(string,string,n) compares the first n characters of two strings for equality. The function returns a scalar logical 1 for equality, or scalar logical 0 for inequality.
TF = strncmp(string,cellstr,n) compares the first n characters of a string with the first n characters of each element of a cell array of strings. The function returns a logical array the same size as the cellstr input in which logical 1 represents equality. The order of the first two input arguments is not important.
TF = strncmp(cellstr,cellstr,n) compares each element of one cell array of strings with the same element of the other. strncmp attempts to match only the first n characters of these strings. The function returns a logical array the same size as either input array.
string |
Single character string or n-by-1 array of strings. |
cellstr |
Cell array of strings. |
n |
Maximum number of characters to compare. Must be a scalar, integer-valued double. |
Before trying the strncmp function, use strcmp to perform a simple comparison of the two input strings. 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 5-by-10 string 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 DD-DDDDDDD 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