How can I determine whether a string contains a substring?

조회 수: 91 (최근 30일)
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?

채택된 답변

MathWorks Support Team
MathWorks Support Team 2022년 11월 17일
편집: MathWorks Support Team 2022년 11월 17일
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:
  댓글 수: 1
Steven Lord
Steven Lord 2022년 11월 17일
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

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Royi Avital
Royi Avital 2018년 8월 26일
편집: MathWorks Support Team 2022년 11월 29일
I guess that since MATLAB R2016b it is recommended to use `contains` :

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

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

제품


릴리스

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by