function that ouputs the average word length in a string removing all special characters

2 次查看(过去 30 天)
I might be going about this all the wrong way. I need to write a function that ouputs the average word length in a string without any special characters. I think i am having trouble with the syntax and properly writing what i want to say.
function [avg] = averageLength(string)
string = 'i? love? you!'
splitString = split(string,' ');
size = size(splitString);
wordCount = size(1);
i = 1;
while 1<= wordCount
newstring(i) = regexprep(splitString(i),'?''!''*''&''%''"''@''#''$''^''('')''1''2''3''4''5''6''7''8''9''0','');
size(newstring(i))=strlength(newstring(i));
for i=1:wordCount
avg = mean(newString(i));
end
end
end

采纳的回答

David Hill
David Hill 2022-10-20
s = 'i? love? you!';
r=regexprep(s,'[!?"$%&#]','');%whatever special characters
m=mean(cellfun(@(x)length(x),strsplit(r,' ')))
m = 2.6667

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by