C Program to Reverse a String

Here we’ll see how to write a C program to reverse a string.

Solution 1

void reverse_string(char *input, char *output) {
  int len = 0, i = 0;

  if(input == NULL || output == NULL) return;

  len = strlen(input);

  for(i = 0; i < len; i++) {
    output[i] = input[len - i -1];
  }

  output[len] = '\0';
}

The reverse_string() function takes the input string as input parameter and reverses that into the output string. The last character of the input string is set as the first character of the output string, second last character of the input string as second character of output string and so on. Here the original string remains unchanged. The reversed string is set to the output string.

Solution 2

void reverse_string1(char *input) {
  int len = 0, i = 0;
  char tmp;

  if(input == NULL) return;

  len = strlen(input);

  for(i = 0; i < len / 2; i++) {
    tmp = input[i];
    input[i] = input[len - i -1];
    input[len - i -1] = tmp;
  }
}

Here the function reverse_string() iterates for as many times as half of the string length. In every iteration, two characters are swapped. In first iteration first and last characters are swapped, in second iteration second and second last characters are swapped and so on. Here the original string gets reversed.

The Complete Program

#include <stdio.h>
#include <string.h>

void reverse_string(char *input, char *output) {
  int len = 0, i = 0;

  if(input == NULL || output == NULL) return;

  len = strlen(input);

  for(i = 0; i < len; i++) {
    output[i] = input[len - i -1];
  }

  output[len] = '\0';
}

int main(){
  char str[] = "qnaplusdotcom";
  char rev[32];

  reverse_string(str, rev);
  
  printf("Original string: %s\n", str);
  printf("Reverse string: %s\n", rev);

  return 0;
}

The Output:

Original string: qnaplusdotcom
Reverse string: moctodsulpanq

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0