Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I want to create a function that when a string is entered it will turn it into a list of numbers, these numbers are the numerical form of the characters in the string.

e.g. a=1, b=2, c=3, d=4 and space = 27 (other punctuation may be needed).

So if I had the string "hello", my result would be: {8, 5, 12, 12, 15}

I had a look at StringReplace, StringSplit and Characters, but not sure what is optimal.

How would I go about doing this?

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

You can start by using ToCharacterCode then applying whatever rules you want using ReplaceAll.

For example, to get "a" aligned to one we will need to subtract 96 from the ASCII value:

string = "hello world";
rules = {-64 -> 27};
ToCharacterCode[string] - 96
% /. rules
{8, 5, 12, 12, 15, -64, 23, 15, 18, 12, 4}

{8, 5, 12, 12, 15, 27, 23, 15, 18, 12, 4}

Less efficiently but also perhaps easier to work with for mapping a few characters atypically (such as space above) you can do this:

Characters @ string /.
  {" " -> 27, x_String :> ToCharacterCode[x] - 96} // Flatten

{8, 5, 12, 12, 15, 27, 23, 15, 18, 12, 4}

The rules have priority by order therefore ToCharacterCode is only used on the characters you haven't already replaced.


It may help to have a sense of the ASCII mapping:

FromCharacterCode[Range[32, 126]]
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
share|improve this answer
    
Wow, so many hidden features in Mathematica, This is brilliant –  user9053 Aug 15 '13 at 11:42
    
@user9053 Yes, even people who have been using it for years continue to find new things. –  Mr.Wizard Aug 15 '13 at 12:07
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.