How to change ASCII values?
22 次查看(过去 30 天)
显示 更早的评论
I have an assignment where I have to take a phrase, capitalize it, and use the 'double' command to change all of the letters to uppercase. I'm then supposed to loop through the resulting array of letters and change the ASCII values to values like: A=0 B=1 C=2, etc. The problem is that I've tried nearly everything to do that, but so far nothing is working. I was hoping that someone could point out what I am doing wrong and point me in the right direction. Thanks!
Here is what I have so far:
function y=stringcode(k)
k=('Zoinks!')
upper('Zoinks!')
y=double('Zoinks!')
for i=1:length(k)
A=0;
B=1;
C=2;
D=3;
E=4;
F=5;
G=6;
H=7;
I=8;
J=9;
K=10;
L=11;
M=12;
N=13;
O=14;
P=15;
Q=16;
R=17;
S=18;
T=19;
U=20;
V=21;
W=22;
X=23;
Y=24;
Z=25;
end
end
0 个评论
回答(2 个)
Star Strider
2020-1-25
You are not using tthe result of the upper call.
See if:
u = upper(k)
y = double(u)
is more appropriate.
5 个评论
Walter Roberson
2020-1-25
for i=1:length(k)
if k(i) == double('A')
output(i) = 0;
elseif k(i) == double('B')
output(i) = 1;
elseif k(i) == double('C')
output(i) = 2;
all the way to 'Z'
end
end
Star Strider
2020-1-25
‘I'm then supposed to loop through the resulting array of letters and change the ASCII values to values like: A=0 B=1 C=2, etc.’
If you want to replace the elements of ‘y’ by their equivalents in the ‘A=0 B=1 C=2, etc.’ relation you created, you need to compare each one with the alphabetical elements of the relation. Then replace it with the respective value from the numeric equivalent. (There are more efficient ways to do this, however you are apparently supposed to loop through them, so I leave that to you.)
Allen
2020-1-25
I simple way of converting characters values or character vectors to apply a numerical calculation directly to the characters.
k = 'Zoinks!';
y = upper(k)-0; % ASCII values for the uppercase versions of all characters. This includes "!" as well.
% Same as k = str2double(upper(k));
Since the ASCII value of A is 65, if you want to shift the values that are returned such that A = 0 you can do this at the same time you convert to ASCII values.
y = upper(k)-65; % Shifts ASCII values at the same time as converted so that A = 0;
If you need to remove punctuation from the characters you can use regular expressions to do this.
% Replaces anything that is not A-Z with an empty string (including whitespace characters) and converts
% to shifted ASCII values.
y = regexprep(upper(k),'[^A-Z]','')-65;
6 个评论
Star Strider
2020-1-25
@Allen — It is unfortunate that this is not explicitly stated anywhere. We have all had it called to our attnetion at some point.
@Kyle — That happens to us all! See Walter Roberson’s Comment for a hint that is well within the guidelines of the help we can ethically provide.
另请参阅
类别
在 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!