Info

This question is closed. Reopen it to edit or answer.

Help with for loop indexing

1 view (last 30 days)
Ian Connelly
Ian Connelly on 3 Mar 2016
Closed: MATLAB Answer Bot on 20 Aug 2021
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

Answers (1)

Andrei Bobrov
Andrei Bobrov on 3 Mar 2016
st = ' he who sees and he who is not ';
a = regexp(st,'\w*','match');
outStr = strjoin(a(cellfun(@numel,a)>2),' ');

This question is closed.

Community Treasure Hunt

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

Start Hunting!