Clear Filters
Clear Filters

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

2 views (last 30 days)
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

Accepted Answer

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

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!