フィルターのクリア

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 Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by