Cleanups.
[TD_C.git] / TP_7_C / exo3-extra.c
CommitLineData
c2bc2b96
JB
1#include <stdio.h>
2#include <stdlib.h>
3
4int stringLength(const char* str) {
5 int result = 0;
6
7 for (; str[result]; ++result);
8
9 return result;
10}
11
12void swap(char* v1, char* v2) {
13 char temp = *v1;
14 *v1 = *v2;
15 *v2 = temp;
16}
17
18void reverseString(char* str) {
19 char* begin = str;
20 char* end = str + stringLength(str) - 1;
21
22 while (begin < end) {
23 swap(begin++, end--);
24 }
25}
26
27/** Perform a classical ROT13 permutation in-place */
28void rot13(char* str) {
29 char* cursor = str;
30 char* end = str + stringLength(str);
31
32 while (cursor < end) {
33 if (*cursor >= 'a' && *cursor <= 'z') {
34 *cursor = (*cursor - 'a' + 13) % 26 + 'a';
35 } else if (*cursor >= 'A' && *cursor <= 'Z') {
36 *cursor = (*cursor - 'A' + 13) % 26 + 'A';
37 }
38
39 ++cursor;
40 }
41}
42
43int main() {
44 char* msg;
45 puts("Enter your message:");
46 int readValue = scanf("%ms", &msg);
47
48 if (readValue == 0) {
49 puts("oops");
50 return 0;
51 }
52
53 printf("Initial value: \"%s\"\n", msg);
54 reverseString(msg);
55 printf("Reversed : \"%s\"\n", msg);
56 reverseString(msg); // Restore the original message
57 rot13(msg);
58 printf("ROT13 : \"%s\"\n", msg);
59 free(msg); // scanf("%ms") allocate dynamic memory
60}