Compare Character Vectors
You can compare character vectors and cell arrays of character vectors to each other. Use the
strcmp function to compare two character vectors, or strncmp to compare the first N characters.
You also can use strcmpi and strncmpi for case-insensitive comparisons.
Compare two character vectors with the strcmp function. chr1 and chr2 are not equal.
chr1 = 'hello';
chr2 = 'help';
TF = strcmp(chr1,chr2)
TF = logical
0
Note that the MATLAB strcmp differs from the C version of strcmp. The C version of strcmp
returns 0 when two character arrays are the same, not when they are different.
Compare the first two characters with the strncmp function. TF is 1 because both character vectors
start with the characters he.
TF = strncmp(chr1,chr2,2)
TF = logical
1
Compare two cell arrays of character vectors. strcmp returns a logical array that is the same size as
the cell arrays.
C1 = {'pizza'; 'chips'; 'candy'};
C2 = {'pizza'; 'chocolate'; 'pretzels'};
strcmp(C1,C2)
ans = 3x1 logical array
1
0
0
Inspect Characters in String and Character Arrays
You can inspect the characters in string arrays or character arrays with the isstrprop, isletter,
and isspace functions.
• The isstrprop inspects characters in either string arrays or character arrays.
• The isletter and isspace functions inspect characters in character arrays only.
Determine which characters in a character vector are space characters. isspace returns a logical
vector that is the same size as chr.
chr = 'Four score and seven years ago';
TF = isspace(chr)
TF = 1x30 logical array
Compare Text
6-35
Précédent

- 217/1450

Suivant