Member-only story

Comparing Strings (strcmp)

Raheelanjum
2 min readDec 12, 2024

--

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:

Example of Usage

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

Last Warning:

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

--

--

Raheelanjum
Raheelanjum

Written by Raheelanjum

Highly skilled and experienced content writer dedicated to crafting compelling, informative content that resonates with diverse audiences. Expertise spans blog

Responses (7)