MATLAB Answers

tban
0

Transforming a string of letters into number based on each value equaling a number.

tban
さんによって質問されました 2017 年 9 月 20 日
最新アクティビティ Stephen Cobeldick
さんによって コメントされました 2017 年 9 月 20 日
If there are a finite amount of variables available for a string like... a,b,c,d,e....z, and each value is numbered 1,2,3,4,5....26, how can I write a short code to take in a string of letters like "bccddee" and get an output of "2+3+3+4+4+5+5".
I can define each letter as a number, but the 1st problem I encounter is braking up the string into a finite amount of values (7) it contains and then using a loop to go trough them inside the string and add them to the total.
Anyone know how to do this or atleast can point me towards the direction of how I can get within a letter string and convert it to numbers which then i can add?

  0 件のコメント

サインイン to comment.

タグ

製品

4 件の回答

回答者: José-Luis
2017 年 9 月 20 日

str = 'bccddee';
result = sum(str - 'a' + 1)

  1 件のコメント

+1 nice and simple. Why waste time writing anything else?

サインイン to comment.


回答者: tban
2017 年 9 月 20 日

Well, mystring is made out of letters and length is only used for numbers, No?

  0 件のコメント

サインイン to comment.


回答者: tban
2017 年 9 月 20 日

using this and it works, will let you know if i have any more questions
y=char('john') y =john >> length(y) ans = 4
char needs to be used.

  0 件のコメント

サインイン to comment.


回答者: tban
2017 年 9 月 20 日

mystring=char('word')
len=length(mystring)
w=23; o=15;r=18;d=4;
total = 0;
for i = 1:length(mystring)
if (mystring(i) == 'w')
total = total + w;
elseif (mystring(i) == 'o')
total = total + o;
elseif (mystring(i) == 'r')
total = total + r;
elseif (mystring(i) == 'd')
total = total + d;
end
end
this works

  1 件のコメント

Glad it's working, but I don't think you need to use char:
>> length('abcdef')
ans =
6
(works in my command window).

サインイン to comment.



Translated by