0
0
MATLABdata~5 mins

String searching (contains, strfind) in MATLAB

Choose your learning style9 modes available
Introduction

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 is in 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.