Since strings are stored as arrays, we can access the elements of the array and change them directly. For example, we can now write an implementation of the Captain Crunch secret decoder ring easily.
/********************************************* ** File: crunch.c ** Author: R. Chang ** Date: ? ** Modified by: Sue Evans ** Modification date: 9/26/05 ** Section: 101 ** EMail: bogar@cs.umbc.edu * ** Description: ** An implementation of the Captain Crunch ** secret decoder ring. **********************************************/ #include <stdio.h> #include <ctype.h> #define SIZE 25 int main() { char c, str[SIZE] = "this is a secret message"; int index, i; /* Initialize our code */ char code[26] = {'t','f','h','x','q','j','e','m','u','p', 'i','d','c','k','v','b','a','o','l','r', 'z','w','g','n','s','y'} ; /* Print the original phrase */ printf ("Original phrase: %s\n", str); /* Encrypt */ for (i = 0; str[i] != '\0'; i++) { if(isalpha(str[i])) { c = tolower(str[i]) ; index = c - 'a' ; str[i] = code[index] ; } } printf(" Encrypted: %s\n", str ) ; /* Decrypt */ for(i = 0; str[i] != '\0'; i++) { if(isalpha(str[i])) { c = tolower(str[i]) ; /* find matching character */ for(index = 0; index < 26; index++) { if(code[index] == c) { str[i] = 'a' + index ; } } } } printf(" Decrypted: %s\n", str ) ; return 0; }
Original phrase: this is a secret message Encrypted: rmul ul t lqhoqr cqllteq Decrypted: this is a secret message