Info

此问题已关闭。 请重新打开它进行编辑或回答。

Help with for loop indexing

1 次查看(过去 30 天)
Ian Connelly
Ian Connelly 2016-3-3
关闭: MATLAB Answer Bot 2021-8-20
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

回答(1 个)

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

此问题已关闭。

Community Treasure Hunt

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

Start Hunting!

Translated by