How does the function contains behave ??

조회 수: 6 (최근 30일)
Owen Zhang
Owen Zhang 2019년 4월 24일
댓글: Owen Zhang 2019년 4월 24일
Today I'm fixing a bug, because of using contains() function.
There is a condition check whether the input string is exactly in an string array ["Parameter Only","Process Only"]:
The logic is like :
if contains(errtype, ["Parameter Only","Process Only"])
% do something if errtype is any of "Parameter Only","Process Only"
else
% do something if not
end
And what the function "contains" really behaves are out of my expectation, see following test:

채택된 답변

Stephen23
Stephen23 2019년 4월 24일
편집: Stephen23 2019년 4월 24일
The contains function behaves exactly as I would expect, based on its documentation, which states "If pattern is an array containing multiple patterns, then contains returns 1 if it finds any element of pattern in str". Note that it checks if the pattern is in the string (i.e. is part of the string), not if it is equal to the whole string as you seem to think.
For your examples (which you unfortunately uploaded as screenshots, rather than sensibly as text):
  1. The text contains the 1st pattern -> true
  2. The text contains the 2nd pattern -> true
  3. The text does not contain either pattern -> false
  4. The text contains the 2nd pattern -> true
  5. The text does not contain either pattern -> false
So far it is behaving exactly as I would expect. The only problem is that you picked the wrong function for your needs.
Based on your explanation you should be using strcmp or strcmpi, rather than contains:
if any(strcmpi(errtype, ["Parameter Only","Process Only"]))
Or, if errtype is also string class, simply use == and any. Or use switch rather than if.
  댓글 수: 1
Owen Zhang
Owen Zhang 2019년 4월 24일
thank you.
== is easy and clean.
if any(errtype == ["Parameter Only","Process Only"])

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by