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

9 ビュー (過去 30 日間)
Aimee Jin
Aimee Jin 2020 年 11 月 10 日
コメント済み: Aimee Jin 2020 年 11 月 10 日
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

回答 (2 件)

Bruno Luong
Bruno Luong 2020 年 11 月 10 日
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 件のコメント
Aimee Jin
Aimee Jin 2020 年 11 月 10 日
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.

サインインしてコメントする。


Ameer Hamza
Ameer Hamza 2020 年 11 月 10 日
編集済み: Ameer Hamza 2020 年 11 月 10 日
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 件のコメント
Aimee Jin
Aimee Jin 2020 年 11 月 10 日
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 2020 年 11 月 10 日
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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by