MATLAB Answers

0

How can I determine whether a string contains a substring?

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?

Tags

No tags entered yet.

Products


Release

R2017a

3 Answers

Answer by MathWorks Support Team on 16 Jun 2017
 Accepted Answer

You can use 'strfind', which returns an empty array when the substring is not found. For example, the following code returns a value of TRUE when smallSubstring is not found within largeString, false when found. (So negate this expression if you want to know if it is in there or not). 
>> smallSubstring = '0.0100';
>> largeString1 = 'Item0.0100';
>> largeString2 = 'Item0.0101';
>> isempty(strfind(largeString1, smallSubstring))
ans =
  logical
   0
>> isempty(strfind(largeString2, smallSubstring))
ans =
  logical
   1
You may find more information on 'strfind' in the documentation at the following link:

  1 Comment

contains(largeString1, smallSubstring)
The above line will also work and gives logical output similar to your example. Thanks!

Sign in to comment.


Answer by Royi Avital on 26 Aug 2018
Edited by Royi Avital on 26 Aug 2018

I guess that since MATLAB R2016b it is recommended to use `contains` :
https://www.mathworks.com/help/matlab/ref/contains.html

  0 Comments

Sign in to comment.


Answer by Praveen Manupati on 12 Jul 2019 at 13:53

contains(largeString1, smallSubstring)
The above line will also work and gives logical output. Thanks!

  0 Comments

Sign in to comment.