0
0
MATLABdata~5 mins

String comparison in MATLAB

Choose your learning style9 modes available
Introduction
String comparison helps you check if two pieces of text are the same or different. This is useful when you want to make decisions based on words or sentences.
Checking if a user entered the correct password.
Comparing two names to see if they match.
Finding if a word exists in a list of words.
Sorting a list of words alphabetically.
Filtering data based on text labels.
Syntax
MATLAB
tf = strcmp(str1, str2)
tf = strcmpi(str1, str2)
strcmp compares two strings and returns logical true (1) if they are exactly the same, logical false (0) otherwise.
strcmpi does the same but ignores uppercase or lowercase differences.
Examples
Returns true because both strings are exactly the same.
MATLAB
result = strcmp('hello', 'hello')
Returns false because the case is different.
MATLAB
result = strcmp('Hello', 'hello')
Returns true because strcmpi ignores case differences.
MATLAB
result = strcmpi('Hello', 'hello')
Sample Program
This program compares two strings first with case sensitivity, then ignoring case, and prints the result.
MATLAB
str1 = 'Matlab';
str2 = 'matlab';

if strcmp(str1, str2)
    disp('Strings are exactly the same.')
elseif strcmpi(str1, str2)
    disp('Strings are the same ignoring case.')
else
    disp('Strings are different.')
end
OutputSuccess
Important Notes
Use strcmp for exact matches including case.
Use strcmpi when you want to ignore uppercase or lowercase differences.
Both functions return logical true (1) or false (0), which you can use in if statements.
Summary
String comparison checks if two texts are the same or different.
Use strcmp for case-sensitive comparison.
Use strcmpi for case-insensitive comparison.