Programming |
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.
Strings str1
and str2
are not identical, so invoking strcmp
returns logical 0
(false
). For example,
Note
For C programmers, this is an important difference between the MATLAB strcmp and C's strcmp() , which 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
:
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:
isletter
determines if a character is a letter
isspace
determines if a character is white space (blank, tab, or new line)
isstrprop
checks characters in a string to see if they match a category you specify, such as
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.
Cell Arrays of Strings | Searching and Replacing |
© 1994-2005 The MathWorks, Inc.