String Comparisons

There are several ways to compare strings and substrings:

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

Comparing Strings for Equality

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

  • strcmp determines if two strings are identical.

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

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

Consider the two strings

str1 = 'hello';
str2 = 'help';

Strings str1 and str2 are not identical, so invoking strcmp returns logical 0 (false). For example,

C = strcmp(str1,str2)  
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 strings are the same.

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

C = strncmp(str1, str2, 2)
C =

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

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

Now apply the string 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 strings:

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

A == B
ans =
    0   1   0   1

All of the relational operators (>, >=, <, <=, ==, ~=) compare the values of corresponding characters.

Categorizing Characters Within a String

There are three functions for categorizing characters inside a string:

  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 string 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 string named mystring:

mystring = 'Room 401';

isletter examines each character in the string, producing an output vector of the same length as mystring:

A = isletter(mystring)
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 mystring are letters.

Was this topic helpful?