On command line, we want to reverse the parameters, we can compile the following C program to produce a exectuable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> #include <string.h> void reverse(char *buf, int i, int j) { while (i < j) { char t = buf[i]; buf[i] = buf[j]; buf[j] = t; i ++; j --; } } int main(int argc, char* argv[]) { if (argc == 0) { return 0; } for (int i = 1; i < argc; ++ i) { int l = strlen(argv[i]); reverse(argv[i], 0, l - 1); printf("%s\n", argv[i]); } return 0; } |
#include <stdio.h> #include <string.h> void reverse(char *buf, int i, int j) { while (i < j) { char t = buf[i]; buf[i] = buf[j]; buf[j] = t; i ++; j --; } } int main(int argc, char* argv[]) { if (argc == 0) { return 0; } for (int i = 1; i < argc; ++ i) { int l = strlen(argv[i]); reverse(argv[i], 0, l - 1); printf("%s\n", argv[i]); } return 0; }
To reverse a string is easy – we can use the two pointer to swap the characters at both pointer and move them towards each other until they meet in the middle.
To compile the above C code:
1 | $ gcc reverse.c -o rev |
$ gcc reverse.c -o rev
Example usage:
1 2 3 4 5 6 7 | $ ./rev abc cba $ ./rev abc def cba fed $ ./rev "123 456" 654 321 |
$ ./rev abc cba $ ./rev abc def cba fed $ ./rev "123 456" 654 321
As you see, we can reverse each parameters, or we can reverse all by wrapping parameters in a quote.
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
238 wordsloading...
Last Post: Teaching Kids Programming - Length of Longest Balanced Subsequence
Next Post: Teaching Kids Programming - Sum of Unique Elements