X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=TP_7_C%2Fexo3-extra.c;fp=TP_7_C%2Fexo3-extra.c;h=36fdb648b868e82a13ff7ed577bb1ceb0aee7a59;hb=c2bc2b96a16dbea260d81c674abd5ac53687c273;hp=0000000000000000000000000000000000000000;hpb=e1b5a0c2efdaae55cb7ccb02126766c41b33afa4;p=TD_C.git diff --git a/TP_7_C/exo3-extra.c b/TP_7_C/exo3-extra.c new file mode 100644 index 0000000..36fdb64 --- /dev/null +++ b/TP_7_C/exo3-extra.c @@ -0,0 +1,60 @@ +#include +#include + +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 +}