how to use "strfind" to search for a word?
5 次查看(过去 30 天)
显示 更早的评论
how to use "strfind" to search for a word and if found return 1 if not return 0
0 个评论
回答(2 个)
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).
0 个评论
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));
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));
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!