Testing for the presence of a substring in a cell array of strings
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Schuyler
am 12 Okt. 2012
Bearbeitet: Leo Simon
am 25 Apr. 2020
*NEWBIE WARNING***
I have a very basic question but couldn't find an answer after searching.
I wish to test if a multi-element cell array of strings contains a substring anywhere within the cell array's text, returning a logical true or false answer. For example, given the cell array of strings x:
x = {'qwer','asdf','zxcv'};
I wish to test if the substring 'xc' is present somewhere in x's text (true in this example).
The method I came up with is as follows:
First, concatenate the elements of the cell array of strings into a single character string, preserving the original character order:
y = char(x);
y = y';
y = y(:)'; % y now equals 'qwerasdfzxcv'
Then, test for the presence of the substring in the concatenated string:
~isempty(strfind(y,'xc')) % ans = true
~isempty(strfind(y,'123')) % ans = false
Is there a better way to do this that involves less array manipulation? Thank you for your assistance.
0 Kommentare
Akzeptierte Antwort
Sean de Wolski
am 12 Okt. 2012
matches = strfind(x,'xc');
tf = any(vertcat(matches{:}))
Weitere Antworten (4)
per isakson
am 12 Okt. 2012
Bearbeitet: per isakson
am 12 Okt. 2012
Here is a construct without implicit casting of types
is_xc = not( cellfun( @isempty, strfind( x, 'xc' ) ) );
and next
any( is_xc )
Easier to read
is_xc = cellfun( @has_value, strfind( x, 'xc' ) ) );
where
function has = has_value( input )
has = not( isempty( input ) );
end
0 Kommentare
Azzi Abdelmalek
am 12 Okt. 2012
Bearbeitet: Azzi Abdelmalek
am 12 Okt. 2012
x = {'qwer','asdf','zxcv'};
out=any(cell2mat(cellfun(@(y) regexp(y,'xc'),x,'un',0)))
or
out=any(cell2mat(regexp(x,'xc')))
0 Kommentare
Demetrio Rodriguez Tereshkin
am 24 Jul. 2015
OP has already given, in my opinion, the best answer. Although it has to be corrected: isempty() always returns 1 for the type "cell", therefore we should use
cellfun(@isempty,strfind(y,'123'))
0 Kommentare
Schuyler
am 12 Okt. 2012
Bearbeitet: Schuyler
am 14 Okt. 2012
1 Kommentar
Leo Simon
am 25 Apr. 2020
Bearbeitet: Leo Simon
am 25 Apr. 2020
This code extends AA's answer to when you need to check if a substring of a string is contained in a cell array:
needLatexForThese = {'\bar','\ubar','\check','\hat'};
stringYes = '$\bar{x}$'
stringNo = '$x^\ast$'
f = @(s) any(cell2mat(cellfun(@(y) contains(s,y),needTexForThese,'un',0)));
f(stringYes)%returns 1
f(stringNo)%returns 0
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!