필터 지우기
필터 지우기

how to use "strfind" to search for a word?

조회 수: 4 (최근 30일)
Amr Hashem
Amr Hashem 2015년 5월 18일
답변: D Hanish 2022년 9월 16일
how to use "strfind" to search for a word and if found return 1 if not return 0

답변 (2개)

Geoff Hayes
Geoff Hayes 2015년 5월 19일
amr - strfind returns the starting index of the pattern within the string so it won't necessarily return one. And this function will return an empty matrix if the pattern cannot be found in the string. If you want to return a one (true) or zero (false) then you could wrap this function within an anonymous function. Something like
isPatternInString = @(string,pattern)~isempty(strfind(string,pattern));
You could then call the above in place of strfind as
string = 'amr';
pattern = 'xyz';
if isPatternInString(string,pattern)
fprintf('pattern is in string!\n');
else
fprintf('pattern is not in string!\n');
end
We pass the string and pattern into the anonymous function and rely on it to determine if the pattern is in the string: if the result of strfind is an empty array, then isempty returns true and we apply the logical not (with the tilde) to get the desired answer of 0 (false).

D Hanish
D Hanish 2022년 9월 16일
It seems to me Geoff's solution is correct, but the addition of an anonymous function obfuscates it needlessly.
simply use
~isempty(strfind(string(myString),pattern));
Unrecognized function or variable 'myString'.
be careful that iin Geoff's solution if "string" is a cell, this function will fail because the result will be a cell and isempty will fail. <grumble> typesafe anyone? anbiguous string mess </grumble>
So simply
myString = 'C:\Users\HNS\MachineLearning\API';
pattern = 'API';
fnd = ~isempty(strfind(string(myString),pattern));

카테고리

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