C Program to Reverse a String

«
»

Reverse a String in C: Reversing a string means replacing the last element in the first position and vice versa and doing it for all characters in a string. For example, the first character is swapped with the last character, the second character is swapped with the second last character and so on.

A string whose reverse string is the same as the original string is called a palindrome.

Examples:

Input string: “hello”
Reversed String: “olleh”

Input string: “Sanfoundry C Programming”
Reversed string: “gnimmargorP C yrdnuofnaS”

Problem Description

Write a program to reverse a string in C.

Problem Solution

There are several ways to reverse a string in C language. Let’s take a detailed look at all the approaches to reverse a string in C.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement

Method 1: Reverse a String in C using Loops (Naive Approach)

In this approach, we have one variable pointing at the first index and one at last. In each step we swap both characters, increment the first variable and decrement the second variable until the first is less than the second one.

Examples:
Input string: “hello world”
“hello world” will be reversed to “dlrow olleh”
Reversed string: “dlrow olleh”

Program/Source Code

Here is the source code of the C program to reverse a string using loops. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

/* 
 *  C program to reverse a string using loops
 */
#include<stdio.h>
#include<string.h>
 
int main() 
{
    char str[20];
    printf("Enter String: ");
    gets(str);
    printf("Entered string is: %s\n",str);
    int start=0,end=strlen(str)-1;
 
    // Start variable points at the start of the string
    // End Variables points at the last index of the string
    while(start<end)
    {
        //Swapping characters at start and end
        char temp=str[start];
        str[start]=str[end];
        str[end]=temp;
 
        //Incrementing start and decrementing end
        start++;
        end--;
    }
    printf("Reversed string is: %s",str);
 
    return 0;
}
Program Explanation

1. Start the program.
2. Take a string as input.
3. Declare two variables pointing to the first and last index of the string.
4. Swap the characters at their places and increment variables pointing to first character and decrement variable pointing to last character.
5. Do it until the first variable is less than the second one.
6. Print the Reversed String.
7. End the Program.

Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).

Space Complexity: O(1)
Since no auxiliary space is required, time complexity is O(1).

Program Output

Here we enter the string “hello world” as input.

advertisement
 
Enter String: hello world
Entered string is: hello world
Reversed string is: dlrow olleh

Method 2: Reverse a String in C using Recursion

In Recursive Approach, we swap the character at index i with character at index (n-i-1), where n is the size of the string, until i reaches the middle of the string.

Examples:
Input string: “hello world”
“hello world” will be reversed to “dlrow olleh”
Reversed string: “dlrow olleh”

Program/Source Code

Here is the source code of the C program to reverse a string using recursion. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

advertisement
/* 
 *  C program to reverse a string using recursion
 */
#include <stdio.h>
#include<string.h>
char* reverse(int start,int mid,int n, char str[20])
{
    // Base Condition
    if(start==mid)
    return str;
    char temp=str[start];
    str[start]=str[n-1-start];
    str[n-1-start]=temp;
 
    // Recursive Calls
    return reverse(start+1,mid,n,str);
}
int main() 
{
    char str[20];
    printf("Enter String: ");
    gets(str);
    printf("Entered string is: %s\n",str);
    int start=0,end=strlen(str)-1;
    int mid=(start + end)/2;
    printf("Reversed string is: %s",reverse(0,mid,end+1,str));
    return 0;
}
Program Explanation

1. Start the program.
2. Take a string as input.
3. Declare a function to reverse a string which recursively calls itself to reverse the string with base condition to stop when half of the string is traversed.
4. Call the function for further reversal of characters.
5. Print the Reversed String.
6. End the Program.

Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).

Space Complexity: O(1)
Since no auxiliary space is required, time complexity is O(1).

Program Output

Here we enter the string “hello world” as input.

 
Enter String: hello world
Entered string is: hello world
Reversed string is: dlrow olleh

Method 3: Reverse a String in C using Functions

In this approach, we declare a function in which we swap strings with an approach similar to naive approach and then simply return that string.

Examples:
Input string: “Sanfoundry C Programming”
“Sanfoundry C Programming” will be reversed to “gnimmargorP C yrdnuofnaS”
Reversed string: “gnimmargorP C yrdnuofnaS”

Program/Source Code

Here is the source code of the C program to reverse a string using functions. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

/* 
 *  C program to reverse a string using functions
 */
#include <stdio.h>
#include<string.h>
char* reverse(int start,int end, char str[20])
{
    // Start variable points at the start of the string
    // End Variables points at the last index of the string
    while(start<end)
    {
        //Swapping characters at start and end
        char temp=str[start];
        str[start]=str[end];
        str[end]=temp;
 
        //Incrementing start and decrementing end
        start++;
        end--;
    }
    //Returning reversed string
    return str;
}
int main()
{
    char str[20];
    printf("Enter String: ");
    gets(str);
    printf("Entered string is: %s\n",str);
    int start=0,end=strlen(str)-1;
    printf("Reversed string is: %s",reverse(0,end,str));
 
    return 0;
}
Program Explanation

1. Start the program.
2. Take a string as input.
3. Declare a function to reverse a string which swaps the character with their corresponding characters. (Ideology is the same as naive approach)
4. Call the function.
5. Print the Reversed String.
6. End the Program.

Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).

Space Complexity: O(1)
Since no auxiliary space is required, time complexity is O(1).

Program Output

Here we enter the string “Sanfoundry C Programming” as input.

 
Enter String: hello world
Entered string is: Sanfoundry C Programming
Reversed string is: gnimmargorP C yrdnuofnaS

Method 4: Reverse a String in C using strrev Function (Inbuilt Function)

In this approach, we declare a string and pass it call strrev(), an inbuilt function which takes a string and then print the reversed string (strrev is a non standard function, so won’t work on modern compilers).

Program/Source Code

Here is the source code of the C program to reverse a string using strrev Function. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

/* 
 *  C program to reverse a string using strrev Function
 */
#include<stdio.h>  
#include <string.h>    
int main()
{    
    char str[20]="I love Sanfoundry";    
    printf("String is: %s",str);    
    printf("\nReversed String is: %s",strrev(str));    
    return 0;    
}
Program Explanation

1. Start the program.
2. Declare a String.
3. Call the strrev() function and print the reversed string.
4. End the program

Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).

Space Complexity: O(1)
Since no auxiliary space is required, time complexity is O(1).

Program Output

Here we enter the string “I love Sanfoundry” as input.

 
String is: I love Sanfoundry
Reversed String is: yrdnuofnaS evol I

Method 5: Reverse a String in C using Pointers

In this approach, we reverse the string using the pointers. First pointer points at the start of the string and second at the last and in each iteration we swap the two characters and increment and decrement respectively.

Program/Source Code

Here is the source code of the C program to reverse a string using pointers. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

/* 
 *  C program to reverse a string using pointers
 */
#include<stdio.h>
#include<string.h>
char *rev_string(char *str)
{
    //start points to start, end points to last and temp is for swapping two characters
    char *start,*end,temp;
    start=str;
    end=str;
    int len=strlen(str);
 
    //pointing end to last character
    for(int i=0;i<len-1;i++)
    end++;
    for(int i=0;i<len/2;i++)
    {
        //Swapping characters at start and end places
        temp=*start;
        *start=*end;
        *end=temp;
 
        //Incrementing start and decrementing end character
        start++;
        end--;
    }
    return str;
}
int main() 
{
    char str[50];
    printf("Enter String: ");
    gets(str);
    char *rev=rev_string(str);
    printf("Reversed String is: %s",rev);
 
    return 0;
}
Program Explanation

1. Start the program.
2. Take a string as input.
3. Declare a function to reverse a string which takes a string as parameter.
4. In the function:

  • Declare two pointers start and end.
  • Initially Start and end both points at the first character of string.
  • Iterate end to end of the string.
  • Now swap characters at start and end until start is less than end.
  • Return the reversed string.

5. Print the Reversed String.
6. End the Program.

Time Complexity: O(n)
In the above program, we are traversing the string so time complexity is O(n).

Space Complexity: O(1)
Since no auxiliary space is required, time complexity is O(1).

Program Output

Here we enter the string “hello world” as input.

 
Enter String: I love Sanfoundry
Reversed String is: yrdnuofnaS evol I

Method 6: Reverse a String in C using 2D Array

In this approach, we will reverse every word of given string using 2D array.

Program/Source Code

Here is source code of the C Program to reverse every word of given string. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /* 
  2.  *  C Program to Reverse every Word of given String using 2D Array
  3.  */
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. void main()
  8. {
  9.     int i, j = 0, k = 0, x, len;
  10.     char str[100], str1[10][20], temp;
  11.  
  12.     printf("Enter the string: ");
  13.     scanf("%[^\n]s", str);
  14.  
  15. /* reads into 2d character array */
  16.     for (i = 0;str[i] != '\0'; i++)
  17.     {
  18.         if (str[i] == ' ')
  19.         {
  20.             str1[k][j]='\0';
  21.             k++;
  22.             j=0;
  23.         }
  24.         else
  25.         {
  26.             str1[k][j]=str[i];
  27.             j++;
  28.         }
  29.     }
  30.     str1[k][j] = '\0';
  31.  
  32. /* reverses each word of a given string */
  33.     for (i = 0;i <= k;i++)
  34.     {
  35.         len = strlen(str1[i]);
  36.         for (j = 0, x = len - 1;j < x;j++,x--)
  37.         {
  38.             temp = str1[i][j];
  39.             str1[i][j] = str1[i][x];
  40.             str1[i][x] = temp;
  41.         }
  42.     }
  43.     for (i = 0;i <= k;i++)
  44.     {
  45.         printf("%s ", str1[i]);
  46.     }
  47. }
Program Explanation

1. Take a string as input and store it in the array str[].
2. Using for loop store each word of the input string into the 2-D array str1[][].
3. In the 2-D array str1[][] reverse each word of the string at each row of the array.
4. Print the 2-D array as output.

Program Output

Here we enter the string “C Programming Class” as input.

Enter the string: C Programming Class
C gnimmargorP ssalC

Method 7: Reverse a String in C using Recursion and Iteration

In this approach, we will reverse using both recursion and iteration.

Program/Source Code

Here is source code of the C Program to reverse the string using both recursion and iteration. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/*
 *  C Program to Reverse the String using Both Recursion and Iteration
 */
#include <stdio.h>
#include <string.h>
 
/* Function Prototype */
void disp_str1_rec(char *);
 
void main()
{
    char str1[100], *ptr;
    int len1 = 0, i;
    char ch;
    printf("Enter the string:\n");
    scanf("%[^\n]s", str1);
    ptr = str1;
    len1 = strlen(str1);
    printf("Using iteration:\n");
    for (i = len1 - 1; i >= 0;i--)        /* Iterative loop */
    {
 
        ch = str1[i];
        printf("%c", ch);
    }
    printf("Using recurssion:\n");
    disp_str1_rec(ptr);
}
 
/* Code to reverse the string using Recursion */
void disp_str1_rec(char *stng)
{
    char ch;
    if (*stng != '\0')
    {
        ch = *stng;
        stng++;
        disp_str1_rec(stng);
        printf("%c", ch);
    }
    else
    return;
}
Program Output
Enter the string:
welcome to sanfoundry's c programming class
 
Using iteration:
ssalc gnimmargorp c s'yrdnuofnas ot emoclew
Using recurssion:
ssalc gnimmargorp c s'yrdnuofnas ot emoclewi

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.