Help with for loop indexing
Infos
Cette question est clôturée. Rouvrir pour modifier ou répondre.
Afficher commentaires plus anciens
Hey, I'm trying to figure this question in Cody Coursework out where I'm given a string in as an input and I'm supposed to delete all of the extra spaces and words with two or less letters within them. So for example, ' he who sees and he who is not ' should be : 'who sees and who not' I think the problem is that I shouldn't run the for loop to a variable that is changing within the loop, but I'm unsure as to what to do to it. The assignment is due in 40 mins so I don't know if anyone will be able to help, but for what it's worth here it is:
function outStr = remove_small_words(inStr)
c1 = 1;
str = strtrim(inStr);
endS = numel(str);
for c1 = 1:endS
while c1 ~= endS
if (str(c1) == char(32) && str(c1+1) == char(32))
str(c1) = [];
c1 = c1 - 1;
elseif (str(c1) == char(32) && str(c1+2) == char(32))
str(c1+2) = [];
str(c1+1) = [];
c1 = c1 - 1;
elseif (str(c1) == char(32) && str(c1+3) == char(32))
str(c1+3) = [];
str(c1+2) = [];
str(c1+1) = [];
c1 = c1 - 2;
elseif (str(c1) == endS - 2)
break
end
c1 = c1 + 1;
end
outStr = str;
end
Any help is appreciated, thanks
Réponses (1)
Andrei Bobrov
le 3 Mar 2016
st = ' he who sees and he who is not ';
a = regexp(st,'\w*','match');
outStr = strjoin(a(cellfun(@numel,a)>2),' ');
Cette question est clôturée.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!