how to use "strfind" to search for a word?
12 views (last 30 days)
Show older comments
how to use "strfind" to search for a word and if found return 1 if not return 0
0 Comments
Answers (2)
Geoff Hayes
on 19 May 2015
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 Comments
D Hanish
on 16 Sep 2022
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 Comments
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!