Comparing Strings (strcmp)

In Matlab (or C), when comparing strings (which are just arrays of characters) you should always use the strcmp (string compare) function. You are probably now used to using == to mean the equality test, and thus want to use it to see if two strings are the same. Do Not. In this case == means character by character comparison, and if the strings are of different lengths, an error will end your program.

String Compare

Strings are arrays of characters. We often use them to represent information to the user of our programs. Sometimes we use them to store information about the state of our program. When we do so, we will often want to "test" this state. To do so we need the strcmp function.

The function "strcmp" is used when comparing two strings for equality in Matlab. The strcmp function takes two input arguments (two strings) and returns either true or false, just like any boolean expression. Strcmp will only return true if every character of both strings is the same and they are the same length. In all other cases, strcmp will return false.

Here is an example of using strcmp:

        
        strcmp('this', 'that') % strcmp is a function that returns true or false

        favorite_animal = input('what is your favorite animal? ','s');
        favorite_dog    = input('what is your favorite type of dog? ','s');

        if ( strcmp( favorite_dog, favorite_animal ) )
          fprintf('Your favorite animal is a type of dog!\n');
        end
        
      

Example of Usage

Here is an example of using the input function and strcmp to gather valid input from the user:

        
        input_value = input('is Jim your prof? (y/n) ','s');

        % save the result, of the input_value being compared to the character 'y',
        % in the variable "jim_is_the_prof"
        
        jim_is_the_prof = strcmp(input_value, 'y');

        %
        % Now do something based on this information.
        %
        if ( jim_is_the_prof )
          % do something
        end
        
      

Last Warning:

MEMORIZE THIS: when comparing two strings, we always use the strcmp function, we should never use the double equals.



Back to Topics List