How to get Mathmatica to ignore spaces in a cypher

Clear[x, y, z]
ToCharacterCode["abcdefghijklmnopqrstuvwxyz"];
secretMessage[s_, n_] := FromCharacterCode[ToCharacterCode[s] + n] ;
secretMessage["hello world", 3] == "khoor zruog" (*Outputs false when it should be true*)
secretMessage["hello world", 3];
secretMessage[%, -3] == "hello world" (*Correctly outputs as true*)


The code outputs False and True. For whatever reason, the space outputs as a "#" and I can't figure out how to make it ignore it and just go ahead with the test. I basically want the space to be ignored when I am evaluating the function.

• Happy to try to help, but would you please post your code as something other than an image. I find that using triple backslash to be a handy way to delimit code from comments. – Mark R Feb 27 at 3:43
• Sorry about that I hope this is better – Jimmy Stevens Feb 27 at 3:51
• Much - thanks. Let me take a look and see if I can help. – Mark R Feb 27 at 4:09
• What is your first "ToCharacterCode" supposed to do? Also, please use "(" and ")" to delimit comments rather than "\\\". Also, why do you think that the space character should be idempotent? When I convert using your function, I get "khoor#zruog". If you want the conversion of space to be idempotent (returning space), then you need to modify your function. – Mark R Feb 27 at 4:14
• I'm attempting to create a shift cipher so the character code is just the letters of the alphabet. I really just want the space to be left alone by the function rather than converted to a "#". That is what I assume is what returns the first statement as false when it is true. Sorry for all the poor formatting I will be sure to do that next time. – Jimmy Stevens Feb 27 at 4:31

It seems that you want the space character to be idempotent, so try this:

secretMessage[s_, n_] :=
FromCharacterCode[If[# == 32, 32, # + n] & /@ ToCharacterCode[s]];
secretMessage["hello world",
3] == "khoor zruog" (* outputs false when should be true *)

secretMessage["hello world", 3];
secretMessage[%, -3] == "hello world" (* correctly outputs true *)


It now returns True and True.

Also, if you want a more general version of the function, try this:

secretMessage[s_, n_, ignoreCharacters_List : {32}] :=
FromCharacterCode[
If[MemberQ[ignoreCharacters, #], #, # + n] & /@ ToCharacterCode[s]]


It will allow you to put any arbitrary ignore list into the function. As written, the default value is 32, which denotes the space character. If you want others, you could easily do something like this:

secretMessage["hello world-this that", 3, ToCharacterCode[" -"]]


And you will see that the space and the dash are preserved.

• That worked, thank you so much! – Jimmy Stevens Feb 27 at 4:34