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.

Text Comparisons

There are several ways to compare character arrays and subarrays:

These functions work for both character arrays and cell arrays of character vectors.

Compare Character Arrays for Equality

You can use any of four functions to determine if two input character arrays are identical:

  • strcmp determines if two character arrays are identical.

  • strncmp determines if the first n characters of two character arrays are identical.

  • strcmpi and strncmpi are the same as strcmp and strncmp, except that they ignore case.

Consider the two character vectors

chr1 = 'hello';
chr2 = 'help';

chr1 and chr2 are not identical, so invoking strcmp returns logical 0 (false). For example,

C = strcmp(chr1,chr2)  
C =

    Note   For C programmers, this is an important difference between the MATLAB® strcmp and C strcmp() functions, where the latter returns 0 if the two inputs are the same.

The first three characters of chr1 and chr2 are identical, so invoking strncmp with any value up to 3 returns 1:

C = strncmp(chr1, chr2, 2)
C =

These functions work cell-by-cell on a cell array of character vectors. Consider the two cell arrays of character vectors

A = {'pizza'; 'chips'; 'candy'};
B = {'pizza'; 'chocolate'; 'pretzels'};

Now apply the text comparison functions:

ans =
ans =

Comparing for Equality Using Operators

You can use MATLAB relational operators on character arrays, as long as the arrays you are comparing have equal dimensions, or one is a scalar. For example, you can use the equality operator (==) to determine where the matching characters are in two character vectors:

A = 'fate';
B = 'cake';

A == B
ans =
    0   1   0   1

All of the relational operators (>, >=, <, <=, ==, ~=) compare the values of corresponding characters. For more information on relational operators, see Relational Operations.

Categorize Characters Within Character Array

There are three functions for categorizing characters inside a character array:

  1. isletter determines if a character is a letter.

  2. isspace determines if a character is white space (blank, tab, or new line).

  3. isstrprop checks characters in a character array to see if they match a category you specify, such as

    • Alphabetic

    • Alphanumeric

    • Lowercase or uppercase

    • Decimal digits

    • Hexadecimal digits

    • Control characters

    • Graphic characters

    • Punctuation characters

    • Whitespace characters

For example, create a character vector named chr:

chr = 'Room 401';

isletter examines each character, producing an output vector of the same length as chr:

A = isletter(chr)
A = 
    1   1   1   1   0   0   0   0

The first four elements in A are logical 1 (true) because the first four characters of chr are letters.

Was this topic helpful?