Sangeetha R
Sangeetha R

Reputation: 139

Check any string from a set of substrings available in main String in MATLAB

We have set of sub strings t = (b6,b7,y7,y8) and a main String K ='hgtb6ju\u'.

I need to check whether any of the element in t available in K. If yes, which substring(s).

Upvotes: 2

Views: 83

Answers (3)

DVarga
DVarga

Reputation: 21799

You can use strfind:

t = {'b6', 'b7', 'y7', 'y8', 'ju'};
K = 'hgtb6ju\u';
indexes = find(cellfun(@(x) ~isempty(strfind(K, x)), t));
% indexes == [1, 5] - means: 'b6' and 'ju'
isAny = ~isempty(indexes);

Upvotes: 1

Florian
Florian

Reputation: 1824

A little shorter than the strfind solution (if you have access to R2016b):

K = 'hgtb6ju\u';
t = {'b6', 'b7', 'y7', 'y8', 'ju'};
indices = find(cellfun(@(s) contains(K,s),t));

You can even call contains(K,t) directly, but it will only return a scalar logical indicating whether any of the elements of t is in K, not telling you which. That's what above's cellfun call does.

Upvotes: 1

Sardar Usama
Sardar Usama

Reputation: 19689

t = {'b6', 'b7', 'y7', 'y8', 'ju'};
K = 'hgtb6ju\u';
logidx = ~cellfun(@isempty,regexp(K,t)); %Finding if substrings are present
matched = t(logidx)  % Finding which substrings are present

Upvotes: 1

Related Questions