How can I get the first and last letters out of each word?

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

Answers (2)

Bruno Luong
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'}
  1 Comment
Aimee Jin
Aimee Jin on 10 Nov 2020
Thank you so much for the help! I didn't think of it (i==1 and i==length(str) )!
Also the deletion of "count = count +1" for the last letter is of great help.

Sign in to comment.


Ameer Hamza
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
Aimee Jin
Aimee Jin on 10 Nov 2020
We don't have to use for-loop. But the main functions we can use are "for", "while", "if", "isletter", "isspace", "strcmp", "upper", "num2str".
Rik
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.

Sign in to comment.

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!