How can I get the first and last letters out of each word?
9 views (last 30 days)
Show older comments
This is how I write the function. Basically, if you input sentence "Check adjacent elements 4speical pat-terns", it gives you {'CHECK', 'ADJACENT', ELEMENTS', 'SPECIAL', 'PAT', 'TERNS'}. The question is I tried to give the word = str(beginning letter : ending letter), but the check condition went wrong when it comes to the first letter of the setence (eg. C in check). I don't know how to fix it.
function ca = makeKeyArray(str)
char=isletter(str);
for k=1:length(str)
if strcmp(str(k),'''')==1 || char(k)==1 %set condition
char(k)=1;
end
end
count=0;
for i=1:length(str)-1
if char(i-1)==0 && char(i)==1 %find first letter in word, this is where it goes wrong
count=count+1;
beg(count)= i;
elseif char(i+1)==0 && char(i)==1 %find last letter in word
count=count+1;
close(count)=i;
word(count)=str(beg(count):close(count)); %get word. e.g. word(1) = str(beg(1):close(1)) = str(1:6)
end
end
ca=upper(word);
end
0 Comments
Answers (2)
Bruno Luong
on 10 Nov 2020
Fix few things in your code
function ca = makeKeyArray(str)
char=isletter(str);
for k=1:length(str)
if strcmp(str(k),'''')==1 || char(k)==1 %set condition
char(k)=1;
end
end
count=0;
for i=1:length(str) % FIX HERE
if i==1 || char(i-1)==0 && char(i)==1 % FIX HERE
count=count+1;
beg(count)= i;
elseif i==length(str) || char(i+1)==0 && char(i)==1 % FIX HERE
%count=count+1; % FIX HERE
close(count)=i;
word{count}=str(beg(count):close(count)); % curly bracket
end
end
ca=upper(word);
end
Test
>> makeKeyArray('Check adjacent elements 4speical pat-terns')
ans =
1×6 cell array
{'CHECK'} {'ADJACENT'} {'ELEMENTS'} {'SPEICAL'} {'PAT'} {'TERNS'}
Ameer Hamza
on 10 Nov 2020
Edited: Ameer Hamza
on 10 Nov 2020
You can just use regexp()
str = 'Check adjacent elements 4speical pat-terns';
out = regexp(str, '[A-Za-z]*', 'match')
Result
>> out
out =
1×6 cell array
{'Check'} {'adjacent'} {'elements'} {'speical'} {'pat'} {'terns'}
4 Comments
Rik
on 10 Nov 2020
The best solution by far is to use a regular expression. Failing that, you can use isletter to determine the location of letters. Then you need find a way to separate the runs of trues.
See Also
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!