MATLAB Answers

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?

태그

아직 태그를 입력하지 않았습니다.

제품


릴리스

R2017a

답변 수: 3

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

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

로그인 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

로그인 to comment.


Answer by Praveen Manupati on 12 Jul 2019

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

  댓글 수: 0

로그인 to comment.



Translated by