0
0
MATLABdata~10 mins

String searching (contains, strfind) in MATLAB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String searching (contains, strfind)
Start with string S
Search for substring sub
Return indices of sub
End
The program starts with a main string and a substring to find. It checks if the substring exists inside the main string. If yes, it returns the positions; if no, it returns empty.
Execution Sample
MATLAB
S = 'hello world';
sub = 'lo';
idx = strfind(S, sub);
found = contains(S, sub);
This code searches for 'lo' inside 'hello world' using strfind and contains.
Execution Table
StepVariableValueActionResult
1S'hello world'Initialize main string'hello world'
2sub'lo'Initialize substring to find'lo'
3idx[4]Call strfind(S, sub)Returns [4] because 'lo' starts at position 4
4foundtrueCall contains(S, sub)Returns true because 'lo' is in S
5foundtrueAssign contains result to foundfound = true
💡 Search complete: strfind found index 4, contains returned true
Variable Tracker
VariableStartAfter strfindAfter containsFinal
S'hello world''hello world''hello world''hello world'
sub'lo''lo''lo''lo'
idx[][4][4][4]
foundfalsefalsetruetrue
Key Moments - 2 Insights
Why does strfind return [4] but contains returns true?
strfind returns the starting index of the substring in the main string (4 means 'lo' starts at position 4). contains returns a logical true/false if the substring exists anywhere. See execution_table rows 3 and 4.
What happens if the substring is not found?
strfind returns an empty array [], and contains returns false. This is shown by the exit_note and would be reflected in idx and found variables.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of idx after step 3?
A[4]
B[]
C[1]
Dtrue
💡 Hint
Check the 'Value' column for idx at step 3 in the execution_table.
At which step does the variable 'found' become true?
AStep 2
BStep 5
CStep 4
DStep 3
💡 Hint
Look at the 'found' variable changes in execution_table rows 4 and 5.
If sub = 'xyz' (not in S), what would strfind return?
A[4]
B[1]
C[]
Dtrue
💡 Hint
Recall from key_moments that strfind returns empty array if substring not found.
Concept Snapshot
String searching in MATLAB:
- Use strfind(S, sub) to get indices where sub starts in S
- Use contains(S, sub) to get true/false if sub is in S
- strfind returns empty [] if not found
- contains returns false if not found
- Both help find substrings inside strings
Full Transcript
This visual execution shows how MATLAB searches for a substring inside a string using strfind and contains. We start with a main string S and a substring sub. strfind returns the starting index of sub in S or empty if not found. contains returns true if sub is anywhere in S, otherwise false. The execution table traces variable values step-by-step. Key moments clarify why strfind returns indices and contains returns logical values. The quiz tests understanding of these steps.