Cody question help: Remove all the words that end with "ain"
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
1 comentario
Asif Newaz
el 28 de Oct. de 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)
end
Respuestas (1)
Daniel M
el 28 de Oct. de 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.
regexprep(s1,'\w*ain\>','')
0 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!