Deleting a substring

I am trying to write a program that removes the index of a cell array if it contains a specific string.

For example, if the input to a function is equal ({'Hello how are you?', 'I'm fine thank you', 'Have a nice day!'}, 'you')

, only a string is returned 'Have a nice day!'

.

This is what I have so far (it does not remove the index, only the instances where it occurs):

function d = take_out(v, s)
d = regexprep(v(:), s, '');
end

      

+3


source to share


2 answers


Try the following:

function d = take_out(v, s)
    d = v(cellfun('isempty', regexp(v(:), s)));
end

      



regexp(v(:), s)

returns for each cell v

(possibly empty) a vector with integer indices of each occurrence s

. cellfun('isempty', ...)

checks if these vectors are empty and returns a boolean index that is used to select the corresponding cells v

.

+3


source


This is similar to the case for cellfun

, this will apply the function to each cell element. The function used is to see if a substring is found 'you'

in a cell. If not, then it is carried over to d

.



function d = take_out(v, s)
    d = v(cellfun(@(x) isempty(strfind(x, s)), v));
end

      

+1


source







All Articles