How can I determine whether a string contains a substring?

741 views (last 30 days)
I have directory names that end in '0.0100'. I want to be able to skip certain directories by comparing the substring '0.0100' to the directory name. How can I do this?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 17 Nov 2022 at 5:00
Edited: MathWorks Support Team on 17 Nov 2022 at 9:16
You can use the 'contains' function to determine whether a string contains a given substring or not. Specifically, 'contains' returns true if the first argument contains the second argument and false otherwise. For example:
>> smallSubstring = '0.0100';
>> largeString1 = 'Item0.0100';
>> largeString2 = 'Item0.0101';
>> contains(largeString1, smallSubstring)
ans =
  logical
   1
>> contains(largeString2, smallSubstring)
ans =
  logical
   0
You may find more information about 'contains' at the following documentation page:
  2 Comments
Steven Lord
Steven Lord on 17 Nov 2022 at 15:06
If you only want to detect a substring at the end of the larger string, use endsWith instead of contains. The corresponding function for detecting substrings at the beginning is startsWith.
A = ["MATLAB", "laboratory", "collaboration"];
startsWith(A, "lab")
ans = 1×3 logical array
0 1 0
endsWith(A, "lab", 'IgnoreCase', true) % LAB is close enough to lab
ans = 1×3 logical array
1 0 0
contains(A, "lab")
ans = 1×3 logical array
0 1 1

Sign in to comment.

More Answers (2)

Royi Avital
Royi Avital on 26 Aug 2018
Edited: MathWorks Support Team on 29 Nov 2022 at 3:56
I guess that since MATLAB R2016b it is recommended to use `contains` :

Praveen Manupati
Praveen Manupati on 12 Jul 2019
contains(largeString1, smallSubstring)
The above line will also work and gives logical output. Thanks!

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

No tags entered yet.

Products


Release

R2017a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!