? Simple ROT13 Function ● SmileBASIC Source

Sign In

Register
*Usernames are case-sensitive
Forgot my password

Migrating to a new website for SmileBASIC 4

Simple ROT13 Function

EDIT 1: Updated function with faster searching code. Thanks, Na_trium! EDIT 2: Fixed issue with strings being replaced. Ever heard of ROT13? It's a ciphering function! It maps letters of the alphabet A-M to N-Z, and vise versa. Here's a simple function to implement it into SmileBASIC 4. First, let's set up our function. We'll be using OPTION STRICT so that our variables must be defined before using them. Go into the editor, and type this: OPTION STRICT COMMON DEF ROT13$(S$) This will set up a function, ROT13$(String), which will convert String to its ROT13 counterpart. Next, let's set up our variables. These will be used in our code. OPTION STRICT COMMON DEF ROT13$(S$) VAR I=0 VAR R$=S$+"" VAR L=0 VAR ALPHABET$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" VAR ROT13$="NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" You may have noticed the two really long variables, ALPHABET$ and ROT13$ (not to be confused with our ROT13 function). These are dictionaries. We'll scan through each letter of the string to find which one matches one of the letters in the ALPHABET$ variable, and find its matching ROT13 counterpart using the ROT13$ variable. Let's implement this! OPTION STRICT COMMON DEF ROT13$(S$) VAR I=0 VAR R$=S$+"" VAR L=0 VAR ALPHABET$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" VAR ROT13$="NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" FOR I=0 TO LAST(R$) L=INSTR(0,ALPHABET$,R$[I]) IF L!=-1 THEN R$[I]=ROT13$[L] ENDIF NEXT There! Now our function will do what I mentioned. All we have to do now is have our function return the converted string and end. OPTION STRICT COMMON DEF ROT13$(S$) VAR I=0 VAR R$=S$+"" VAR L=0 VAR ALPHABET$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" VAR ROT13$="NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" FOR I=0 TO LAST(R$) L=INSTR(0,ALPHABET$,R$[I]) IF L!=-1 THEN R$[I]=ROT13$[L] ENDIF NEXT RETURN R$ END That's it! Now our function is ready to go. Run the code to register the function, and type this into direct mode: ?ROT13$("Hello world!") The output should be: Uryyb jbeyq!
Author
HTV04
Updated
Rating
0 votes
Categories
Keywords
1 Comment(s) MZ952 MZ952 Intermediate Programmer I can make programs, but I still have trouble here and there. Programming Strength Third Year My account is over 3 years old Website Reading I like to read books! Hobbies I feel like his code be done in O(n) Edit: DEF ROT13 S$ DIM I:FOR I=0 TO LEN(S$)-1 S$[I]=CHR$((ASC(S$[I])-ASC("A")+13)MOD(ASC("Z")-ASC("A")+1)+ASC("A")) NEXT I END Works for caps, but can probably easily be manipulated to handle lowercase as well Edit2: I see your edit now performs in O(n). Nice