recipes : Text Processing : Comparing two strings


You want to test if two strings are identical.


With numbers you can use the == operator but with strings this impossible. Instead, use the strcmp command. This returns a 1 if the strings match and a 0 otherwise.

strcmp('cat','cat') %Matches so returns 1
strcmp('cat','dog') %Fails to match so returns 0

To do case-insensitive comparsisons you can do one of two things:

strcmp(lower('CAT'),lower('cAt')) %Matches so returns 1
strcmpi('CAT','cAt') %Matches so returns 1

Functions like strcmp that test whether or not something is true will usually return 1 if true and 0 if false. That means you can do the following:

if strcmp(string1,'cat')
    disp('It is a cat!')
It is a cat!

The command lower makes strings lower case. Although not particularly useful here, since using strcmpi is easier, there are instances where using lower is useful. One such example is for ensuring switch statements are case insitive:

animal = 'Chicken';
switch lower(animal)
case {'dog','cat'}
    disp('Animal is carnivore')
case {'chicken','goose'}
    disp('Animal is bird')
    disp('Unknown animal')

>> Animal is bird