前言
转载自MathWorks社区,原文链接如下:
https://ww2.mathworks.cn/matlabcentral/fileexchange/59473-cellstrfind?s_tid=srchtitle_cellstrfind_1
附件是开源代码,免费下载。
一、代码
代码如下:
function [tf, idx] = cellstrfind(C,S,option)
%cellstrfind: for finding strings within a cell aray
%
%Syntax: [tf, idx] = cellstrfind(C, S, option);
% idx = cellstrfind(C, S, option);
%Example: [tf, idx] = cellstrfind(C, 'This is a string', 2);
%
%Input arguments:
%
% - C: Cell-Array, in which to search for the string
% - S: The string to search for in the cell array C
% - option: 1 or 2 (double)
% option = 1:
% Include cell that contain S as part of the string
% [e. g. the string 'This is a string' will be found,
% if S = 'string';]
% option = 2:
% Include only cells that contain a string equal to S
% [e. g. the string 'This is a string' will not be found if
% S = 'string';]
%
%Output arguments:
%
% - idx: Index/Indexes of C containing S
% - tf: True/False (logical) with true for the indexes containing S
%
%Author: Marc Jakobi, 04.10.2016
%
%Credits go to the Matlab Central users: Guillaume, Ian Esten and Jan Simon
%for their contributions regarding the topic in the MATLAB Answers forum.
if nargin < 3
option = 1;
end
if option == 1
tf = ~cellfun('isempty', strfind(C, S));
elseif option == 2
tf = cellfun(@(s) ~isempty(strmatch(S, s, 'exact')), C); %#ok<*MATCH3>
end
if nargout == 2
idx = find(tf);
else
tf = find(tf);
end
end