Quantcast

Documentation Center

  • Trial Software
  • Product Updates

strcmp

Compare strings with case sensitivity

Syntax

Description

example

TF = strcmp(s1,s2) compares two strings for equality. The strings are considered to be equal if the size and content of each are the same. The function returns a scalar logical 1 for equality, or a scalar logical 0 for inequality. The comparison is case sensitive.

Inputs can be two strings, two same-sized cell arrays of strings, or a combination of a string and a cell array.

  • If s1,s2 are strings, TF is a logical scalar.

  • If at least one input is a cell array of strings, TF is a logical array the same size as the cell array.

Examples

expand all

Compare Two Strings

Use strcmp to compare two different strings.

strcmp('Yes' ,'No')
ans =

     0

strcmp returns logical 0 (false) because the two strings are not equal. Use strcmp to compare two equal strings.

strcmp('Yes' ,'Yes')
ans =

     1

The function strcmp returns logical 1 (true) because the two strings are equal.

Compare String and Cell Array of Strings

Use strcmp to compare a string, 'upon', to each element of a cell array of strings.

a = 'upon';
b = {'Once' 'upon'; 
     'a' 'time'};
strcmp(a, b)
ans =

     0     1
     0     0

There is only one occurrence of string a in array b, and that occurs at element b{1, 2}.

Compare Two Cell Arrays of Strings

Use strcmp to compare each element in a cell array of strings to the corresponding element in a second cell array of strings.

c = {'Time' 'flies' 'when'; 
     'you''re' 'having' 'fun.'};
d = {'Time' 'drags' 'when'; 
     'you''re' 'anxiously' 'waiting.'};
strcmp(c, d)
ans =

     1     0     1
     1     0     0

There are three instances of equal strings between c and d. These are 'Time' at indices {1, 1}, 'when' at indices{1, 3}, and 'you''re' at indices {2, 1}.

Input Arguments

expand all

s1,s2 — Strings or cell array of strings to comparestring | cell array of strings

Strings or cell array of strings to compare for equality, specified as two strings or a string and a cell array of strings or two equal-sized cell arrays of strings. The order of the inputs does not effect the comparison results.

Data Types: char | cell

More About

expand all

Tips

  • The strcmp function is intended for comparison of character data. When you use it to compare numeric data, strcmp returns logical 0.

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

  • Any leading or trailing blanks are explicitly included in the comparison.

  • The value returned by strcmp is not the same as the C language convention.

  • strcmp supports international character sets.

See Also

| | | | |

Was this topic helpful?