0
$\begingroup$

I would like to ask you how I can associate a letter with a number in Mathematica. I have a text/string, let's say sentence="hello world!", and I would like to substitute each character with a number. So what I am looking for is something like this:

h-> 1
e-> 2 
l -> 3
l-> 4
o -> 5
(space) -> 6
w-> 7 
and so on
!-> 12 

Of course, the text that I am considering contains more than 12 characters, so I cannot do it manually. Could you help me to understand which function I should consider/create to do that?

Many thanks

$\endgroup$
  • $\begingroup$ does ToCharacterCode[sentence] give what you need? or AssociationThread[Characters[sentence],ToCharacterCode[sentence]] ? $\endgroup$ – kglr Sep 20 at 18:10
  • 1
    $\begingroup$ Are you looking for something like string = "hello world!"; Range[StringLength[string]] which outputs the numbers 1 through 12 in a list? If you're looking for actual replacement rules, how should the code determine what numbers should be associated with repeated characters (like the "ll" in "hello")? $\endgroup$ – MassDefect Sep 20 at 18:12
  • $\begingroup$ Rule @@@ Transpose[{Characters@sentence, Range@StringLength@sentence}] $\endgroup$ – Bob Hanlon Sep 20 at 18:15
  • $\begingroup$ Thanks to all for your help and answers. I was looking for something like what Bob Hanlon suggested. How can I list the associations as in ToCharacterCode (without arrows)? $\endgroup$ – Val Sep 20 at 18:36
1
$\begingroup$

Update:

 MapIndexed[# -> #2[[1]] &, Characters[sentence]]

{"h" -> 1, "e" -> 2, "l" -> 3, "l" -> 4, "o" -> 5, " " -> 6, "w" -> 7, "o" -> 8, "r" -> 9, "l" -> 10, "d" -> 11, "!" -> 12}

To get the numbers only the simplest way is what @MassDefect suggested in a comment above: Range @ StringLength @ sentence.

Original answer:

You can use ToCharacterCode:

ToCharacterCode[sentence]

{104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33}

FromCharacterCode[%]

"hello world!"

Normal @ AssociationThread[Characters[sentence], ToCharacterCode[sentence]] 

{"h" -> 104, "e" -> 101, "l" -> 108, "o" -> 111, " " -> 32, "w" -> 119, "r" -> 114, "d" -> 100, "!" -> 33}

List @@@ Normal @
  AssociationThread[Characters[sentence], ToCharacterCode[sentence]] 

{{"h", 104}, {"e", 101}, {"l", 108}, {"o", 111}, {" ", 32}, {"w", 119}, {"r", 114}, {"d", 100}, {"!", 33}}

Alternatively,

DeleteDuplicates @ Thread[{Characters[sentence], ToCharacterCode[sentence]}] 

or

Thread[{#, Flatten @ ToCharacterCode[#]}] & @ DeleteDuplicates[Characters @ sentence]

both give

{{"h", 104}, {"e", 101}, {"l", 108}, {"o", 111}, {" ", 32}, {"w", 119}, {"r", 114}, {"d", 100}, {"!", 33}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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