How can I get the first and last letters out of each word?
9 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
回答 (2 件)
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'}
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 件のコメント
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 Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!