Cody question help: Remove all the words that end with "ain"

2 visualizzazioni (ultimi 30 giorni)
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) = [];
  1 Commento
Asif Newaz
Asif Newaz il 28 Ott 2019
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)

Accedi per commentare.

Risposte (1)

Daniel M
Daniel M il 28 Ott 2019
You 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.


Scopri di più su Scope Variables and Generate Names in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by