C Program to Reverse Strings on Command Line

in #programming3 years ago

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) --

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

Hello @justyy sir
Today I have delegation you 480 SP. Hope you see it

Thanks! got it

@justyy Sir i have delegate 5050sp to @justyy account. Can you check plz.

Screenshot_20210719-214332_Chrome.jpg

Thanks! got it

Coin Marketplace

STEEM 0.17
TRX 0.16
JST 0.029
BTC 74993.05
ETH 2818.21
USDT 1.00
SBD 2.50