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

2 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

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

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by