I have been stuck in the Cody question: Problem 31. Remove all the words that end with "ain"
for the whole afternoon. My codes below passed the first two tests but failed in the third one, because my codes cannot separate "" and ain. Anyone could help?
function s2 = remAin(s1)
s1_cell = strread(s1, '%s');
[s1_cell{find(not(cellfun('isempty', regexp(s1_cell, '\w*ain\>'))) == 1)}] = deal(' ');
s2 = strjoin(s1_cell');
s2 = strrep(s2, sprintf('%c%c%c', 32,32,32), sprintf('%c%c', 32,32));
if s2(end) == ' ' && s2(end-1) == ' '
s2(end) = [];
end
end
2 Comments
Time DescendingYou are overcomplicating things. You have it with this expression
regexp(s1, '\w*ain\>')
But that just returns a set of indices. You can have it return all the other parts of the sentence using
regexp(s1, '\w*ain\>','split')
% ans = 1×3 cell array
% {'I had to '} {' that "'} {'" is not a word'}
which you could then choose to concatenate.
Even simpler still, is to use regexprep, and replace 'ain' with nothing.
regexprep(s1,'\w*ain\>','')
function s2 = remAin(s1)
% s1 = 'I had to explain that "ain" is not a word';
% expression = '(\w*)ain(\w*)';
expression = '\w*ain\>';
% expression = '\w*ain\s';
% expression = '[rspce.]ain';
% expression = '\w*(\.ain)?';
replace = '';
s2 = regexprep(s1,expression,replace)
end
Sign in to participate