strcmp - Compare strings - MATLAB (original) (raw)

Syntax

Description

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

The input arguments can be any combination of string arrays, character vectors, and cell arrays of character vectors.

example

Examples

collapse all

Compare two different character vectors.

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

strcmp returns 0 because s1 and s2 are not equal.

Compare two equal character vectors.

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

strcmp returns 1 because s1 and s2 are equal.

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

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

tf = 2×2 logical array

0 1 0 0

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

Compare each element in two cell arrays of character vectors.

s1 = {'Time','flies','when'; 'you''re','having','fun.'}; s2 = {'Time','drags','when'; 'you''re','anxiously','waiting.'}; tf = strcmp(s1,s2)

tf = 2×3 logical array

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).

Compare string arrays using strcmp.

s1 = ["A","bc"; "def","G"]; s2 = ["B","c"; "def","G"];

tf = strcmp(s1,s2)

tf = 2×2 logical array

0 0 1 1

You can compare and sort string arrays with relational operators, just as you can with numeric arrays.

Use == to determine which elements of two string arrays are equal.

ans = 2×2 logical array

0 0 1 1

Use < to determine which elements of s1 are less than the corresponding elements of s2 according to ASCII dictionary order.

ans = 2×2 logical array

1 1 0 0

Input Arguments

collapse all

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

Data Types: char | cell | string

Output Arguments

collapse all

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

Tips

Extended Capabilities

expand all

Thestrcmp function fully supports tall arrays. For more information, see Tall Arrays.

Usage notes and limitations:

Version History

Introduced before R2006a