This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.


Compare strings




tf = strcmp(s1,s2) compares s1 and s2 and returns 1 (true) if the two are identical. Otherwise, strcmp returns 0 (false). Text is considered identical if the size and content of each are the same. The return result, tf, is of data type logical.

Inputs can be combinations of character vectors, character arrays, and cell arrays of character vectors.


collapse all

Compare Two Character Vectors

Compare two different character vectors.

s1 = 'Yes';
s2 = 'No';
tf = strcmp(s1,s2)
tf =


strcmp returns 0 because s1 and s2 are not equal.

Compare two equal character vectors.

s1 = 'Yes';
s2 = 'Yes';
tf = strcmp(s1,s2)
tf =


strcmp returns 1 because s1 and s2 are equal.

Find Text in Cell Array

Find the word 'upon' in a cell array of character vectors.

s1 = 'upon';
s2 = {'Once','upon';
tf = strcmp(s1,s2)
tf =

     0     1
     0     0

There is only one occurrence of s1 in array s2, and it occurs at element s2(1,2).

Compare Two Cell Arrays of Character Vectors

Compare each element in two cell arrays of character vectors.

s1 = {'Time','flies','when';
s2 = {'Time','drags','when';
tf = strcmp(s1,s2)
tf =

     1     0     1
     1     0     0

There are three instances of equal elements in s1 and s2. These are 'Time' at indices (1,1), 'when' at indices|(1,3)|, and 'you''re' at indices (2,1).

Input Arguments

collapse all

s1,s2 — Input textcharacter vector | character array | cell array of character vectors

Input text, specified as a character vector, character array, or cell array of character vectors. The order of the inputs does not affect the comparison results.

  • If both s1,s2 are cell arrays of character vectors, then s1,s2 must be the same size.

  • If both s1,s2 are character arrays, then s1,s2 can have different numbers of rows.

  • When comparing a nonscalar cell array and a multirow character array, the cell array must be a column vector with the same number of rows as the character array.

Data Types: char | cell

Output Arguments

collapse all

tf — True or false1 | 0 | logical array

True or false result, returned as a 1 or 0 of data type logical.

  • If both inputs are character arrays, tf is a scalar.

  • If at least one input is a cell array of character vectors, tf is an array the same size as the cell array.

  • If s1 and s2 are a character vector in a scalar cell and a character array with multiple rows, then tf is an n-by-1 array, where n is the number of rows in the character array.

More About

collapse all


  • The strcmp function is intended for comparison of text. If you use strcmp on numeric arrays, it always returns 0.

  • For case-insensitive text comparison, use strcmpi instead of strcmp.

  • The value that strcmp returns is not the same as the C language convention.

Introduced before R2006a

Was this topic helpful?