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:
determines if two strings are identical.
strncmpdetermines if the first
ncharacters of two strings are identical.
strncmpiare the same as
strncmp, except that they ignore case.
Consider the two strings
str2 are not identical, so invoking
strcmp returns logical
false). For example,
For C programmers, this is an important difference between the MATLAB |
The first three characters of
str2 are identical, so invoking
strncmp with any value up to 3 returns
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:
isletterdetermines if a character is a letter
isspacedetermines if a character is white space (blank, tab, or new line)
isstrpropchecks characters in a string to see if they match a category you specify, such as
For example, create a string named
isletter examines each character in the string, producing an output vector of the same length as
The first four elements in
A are logical
true) because the first four characters of
mystring are letters.
|Cell Arrays of Strings||Searching and Replacing|
© 1994-2005 The MathWorks, Inc.