We use string searching to find if a smaller piece of text is inside a bigger text. It helps us check or locate words or characters easily.
To check if a sentence contains a specific word.
To find the position of a word inside a paragraph.
To filter a list of names that include a certain substring.
To detect if a file name has a certain extension.
To search for keywords in user input.
Syntax
MATLAB
result = contains(str, pattern)
positions = strfind(str, pattern)
contains returns true or false if the pattern is found.
strfind returns the starting positions of the pattern in the string.
Examples
This checks if 'world' is inside 'hello world'. It returns true.
MATLAB
tf = contains('hello world', 'world')
This finds all positions of 'o' in the string. It returns [5 8].
MATLAB
pos = strfind('hello world', 'o')
This checks if 'python' is inside the string. It returns false.
MATLAB
tf = contains('MATLAB programming', 'python')
This finds where 'na' appears in 'banana'. It returns [3 5].
MATLAB
pos = strfind('banana', 'na')
Sample Program
This program checks if the word 'love' is in the sentence and prints the positions where it starts.
MATLAB
text = 'I love learning MATLAB';
word = 'love';
% Check if word isin text
found = contains(text, word);
% Find position of word in text
positions = strfind(text, word);
fprintf('Is the word "%s" found? %d\n', word, found);
fprintf('Starting position(s): ');
fprintf('%d ', positions);
fprintf('\n');
OutputSuccess
Important Notes
contains is case-sensitive by default but can be made case-insensitive with extra options.
strfind returns an empty array if the pattern is not found.
Use contains when you only need to know if the pattern exists.
Summary
Use contains to check if a string has a pattern (true/false).
Use strfind to get the exact positions of the pattern in the string.
Both help you find text inside other text easily.
Practice
(1/5)
1. Which MATLAB function returns a logical true or false indicating if a substring exists within a string?
easy
A. contains
B. strfind
C. findstr
D. substring
Solution
Step 1: Understand the purpose of contains
contains returns true or false if a substring is found inside a string.
Step 2: Compare with strfind
strfind returns positions, not logical true/false.
Final Answer:
contains -> Option A
Quick Check:
Logical check for substring = contains [OK]
Hint: Use contains for true/false substring check [OK]
Common Mistakes:
Confusing strfind with contains
Thinking strfind returns true/false
Using findstr which is outdated
2. Which of the following is the correct syntax to find the starting indices of substring 'cat' in string str = 'concatenate' using strfind?
easy
A. contains(str, 'cat')
B. strfind('cat', str)
C. strfind(str, 'cat')
D. strfind(str, cat)
Solution
Step 1: Recall strfind syntax
The first argument is the main string, second is the substring to find.