Add TP 7 correction.
[TD_C.git] / TP_7_C / exo3-extra.c
diff --git a/TP_7_C/exo3-extra.c b/TP_7_C/exo3-extra.c
new file mode 100644 (file)
index 0000000..36fdb64
--- /dev/null
@@ -0,0 +1,60 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+int stringLength(const char* str) {
+    int result = 0;
+
+    for (; str[result]; ++result);
+
+    return result;
+}
+
+void swap(char* v1, char* v2) {
+    char temp = *v1;
+    *v1 = *v2;
+    *v2 = temp;
+}
+
+void reverseString(char* str) {
+    char* begin = str;
+    char* end = str + stringLength(str) - 1;
+
+    while (begin < end) {
+        swap(begin++, end--);
+    }
+}
+
+/** Perform a classical ROT13 permutation in-place */
+void rot13(char* str) {
+    char* cursor = str;
+    char* end = str + stringLength(str);
+
+    while (cursor < end) {
+        if (*cursor >= 'a' && *cursor <= 'z') {
+            *cursor = (*cursor - 'a' + 13) % 26 + 'a';
+        } else if (*cursor >= 'A' && *cursor <= 'Z') {
+            *cursor = (*cursor - 'A' + 13) % 26 + 'A';
+        }
+
+        ++cursor;
+    }
+}
+
+int main() {
+    char* msg;
+    puts("Enter your message:");
+    int readValue = scanf("%ms", &msg);
+
+    if (readValue == 0) {
+        puts("oops");
+        return 0;
+    }
+
+    printf("Initial value: \"%s\"\n", msg);
+    reverseString(msg);
+    printf("Reversed     : \"%s\"\n", msg);
+    reverseString(msg); // Restore the original message
+    rot13(msg);
+    printf("ROT13        : \"%s\"\n", msg);
+    free(msg); // scanf("%ms") allocate dynamic memory
+}