This example provides a function to substitute all characters in a string, which present in first set of characters, by characters from second set. This can be used to substitute l/e/a/s/t/o characters in a string by 1/3/4/5/7/0 accordingly, turning your "Hello World" into "H3110 W0r1d" in single script call, or to replace/swap characters with completely irrelevant ones, providing simple "encryption" (e.g. Caesar cipher or various substitution methods) to challenge the player.
Functional part is presented by a single script, named string_subst(string, from, to), which returns string with all characters from set from replaced by according characters from set to. As long as both from and to are of equal length and do not contain repeating characters, output can be "decrypted" by passing parameters in swapped order, e.g.
var asrc, adst, source, encr, decr; asrc = "0123456789"; // source "alphabet" adst = "3456789012"; // destination "alphabet" source = "51"; // source text encr = string_subst(source, asrc, adst); // "encrypted" text show_message(encr); // Displays "84;" decr = string_subst(encr, adst, asrc); // "decrypted" text show_message(decr); // Displays "51;"
Attached example demonstrates both "encryption" and "decryption", and has nice buttons.
The code is as following:
/// string_subst(string, from, to) // Returns [string], with all occurences of // symbols listed in [from] replaced by according // symbols from [to]. // Can be used for different simple // substitution/rotation ciphers. var index, str, char, pos; index = 1 str = "" // result repeat (string_length(argument0)) { char = string_char_at(argument0, index) pos = string_pos(char, argument1) if (pos > 0) { // if char occurs in source alphabet, add // according one from destination alphabet // to output str += string_char_at(argument2, pos) } else { // otherwise just add itself str += char } index += 1 } return str