Skip to content

Instantly share code, notes, and snippets.

@savaged
Last active March 13, 2023 08:11
Show Gist options
  • Save savaged/2dfb8dda184386f64a540b8f2ece1111 to your computer and use it in GitHub Desktop.
Save savaged/2dfb8dda184386f64a540b8f2ece1111 to your computer and use it in GitHub Desktop.
Some fun with C in a functional programming style
// c-sar-cipher
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
//#include "c-sar-cipher.h"
void run(char* arg, void (*cout)(char*));
void print_string(char* str);
char* apply_cipher(char* input);
char rot13(char c);
char* rot13_for_each(char* input, char* output, size_t len, size_t i);
int main(int argc, char** argv)
{
if (argc != 2)
return 1;
run(argv[1], print_string);
return 0;
}
void print_string(char* str) { printf("%s\n", str); }
void run(char* arg, void (*cout)(char*))
{
cout(apply_cipher(arg));
}
char* apply_cipher(char* input)
{
size_t len = strlen(input);
char* output = (char*)malloc(len + 1);
output = rot13_for_each(input, output, len, 0);
output[len] = '\0';
return output;
}
char* rot13_for_each(char* input, char* output, size_t len, size_t i)
{
if (i == len)
return output;
output[i] = rot13(input[i]);
return rot13_for_each(input, output, len, i + 1);
}
char rot13(char c)
{
if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M'))
return c + 13;
else if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z'))
return c - 13;
else
return c;
}
@savaged
Copy link
Author

savaged commented Mar 12, 2023

gcc c-sar-cipher.c -o rot13

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment