On command line, we want to reverse the parameters, we can compile the following C program to produce a exectuable.
#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:
$ gcc reverse.c -o rev
Example usage:
$ ./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) —
221 wordsLast Post: Teaching Kids Programming - Length of Longest Balanced Subsequence
Next Post: Teaching Kids Programming - Sum of Unique Elements