Programming Previous page   Next Page

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:

Consider the two strings

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

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

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

Now apply the string comparison functions:

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 which characters in two strings match:

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:

For example, create a string named mystring:

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

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


Previous page  Cell Arrays of Strings Searching and Replacing Next page

© 1994-2005 The MathWorks, Inc.