Counting number of certain letters

24 ビュー (過去 30 日間)
Student
Student 2018 年 3 月 18 日
コメント済み: Walter Roberson 2020 年 5 月 17 日
I'm trying to make a code that will output the number of a's and e's in my name. I have a basic understanding that I need to go through each element of the string and test if it's an 'a' or 'e' then add up each time. What am I doing wrong below?
myname = "jonathan"
A = char(myname)
numA=0;
numE=0;
for i=1:1:length(A)
if i == 'a'
numA = numA+1
end
if i == 'e'
numE = numE+1
end
end
disp('The number of As: ');
disp(numA);
disp('The number of Es: ');
disp(numE);

回答 (2 件)

per isakson
per isakson 2018 年 3 月 18 日
編集済み: per isakson 2018 年 3 月 18 日
"What am I doing wrong below?"
  1. "to go through each element of the string" your for-loop is fine
  2. "test if it's an 'a' or 'e' then add up each time" your tests don't test what you want them to test
The loop-counter, i, takes the numerical values 1,2,3,... You test whether this numerical value is equal to a character value. That smells. However, Matlab "thinks" that you want to compare the numerical value to the "ascii-value" of the character, e.g.
>> 97=='a'
ans =
1
Here 1 stands for true
Replace
i == 'a'
by
A(i) == 'a'
to compare the i:th character of A to the character, 'a'

Image Analyst
Image Analyst 2018 年 3 月 18 日
Why not just take the histogram?
myname = 'jonathan'
% Convert to numbers:
myname = lower(myname) - '0' - 48
% Take the histogram.
edges = 1:26;
counts = histcounts(myname, edges)
% counts(1) is the number of "a"s in the word.
% counts(26) is the number of "z"s in the word.
  3 件のコメント
ABDALHADI ABU ZEYNEH
ABDALHADI ABU ZEYNEH 2020 年 5 月 17 日
hello
i am a phd student
i am using matlab, i meet a problem
how to find the occurrence of non consecutive letters
for example
the occurence of ab in aabbb=6 i mean that there are for choices to get a before "b"
in acacbbc we can find the word abc four times,i mean that there are for choices to get a before "b" and "b" before "c"
..
Walter Roberson
Walter Roberson 2020 年 5 月 17 日
Clearer would be
myname = lower(myname) - 'a' + 1;

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

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by