top

Search

C Tutorial

.

UpGrad

C Tutorial

Reverse a String in C

The string reverse approach suggests the change in the sequence of characters in a given string in a way that the string’s last character becomes the first character, and so on, performing the swapping of characters. Let’s dive into the following tutorial and explore various ways to perform string reversal in C!

Introduction

You may encounter a situation where you have to check whether an input string is palindrome or not. A palindrome string stays the same when reversed. Various ways are available if you want to reverse a string in C to check for palindrome or encrypt a text, or other purposes.

When the reverse of a string algorithm is implemented in a particular input string, the string entered in a certain order by the user is entirely reversed. For example, if the input string is “world”, the output string will be “dlrow”, implying the string is not palindrome. 

How to Reverse a String in C?

C program uses different ways to reverse a string entered by the user. A given string can be reversed in the C language by using

Reverse a string using the strrev() function

The strrev() is a built-in function defined in the <string.h> header file. Its syntax is:

char *strrev(char *str)

In the above syntax, str is the string that needs to be reversed. This function takes a single parameter and returns the revised version of the reversed string.

Here’s an example program in C to understand how strrev() function works.

#include<stdio.h>
#include<string.h>
 
int main() 
{
 
char strng[10] = "World";
printf("The input string is %s\n", strng);
 
// strrev function is called on the given string
printf("The reversed string is %s", strrev(strng));
 
return 0;
}

Output:

The input string is Reading
The reversed string is gnideaR

The above program calls the strrev( ) on the given string, and the output displays the reversed string.

Note: Since the strrev function doesn’t belong to the C standard library, you might get an error for the above program if it’s not available on your compiler.

Reverse a String Without Using strrev()

If you want to reverse a string in C without strrev, you can execute the following program. 

#include <stdio.h>
#include <string.h>
 
void reverseString(char* str) 
{
int length = strlen(str);
int a, b;
 
for (a = 0, b = length - 1; a < b; a++, b--) {
        char temp = str[a];
        str[a] = str[b];
        str[b] = temp;
}
}
 
int main() 
{
char str[50];
 
printf("Please enter a string: ");
    fgets(str, sizeof(str), stdin); // it accepts the input string from the user
    str[strcspn(str, "\n")] = '\0'; // it removes trailing newline
 
    reverseString(str);
 
    printf("The reversed string is: %s\n", str);
 
return 0;
}

Output:

Please enter a string: Dance
The reversed string is: ecnaD

As seen from the above program, the reverseString function reverses the entered string str. It does this by swapping characters from the start and end of the string using a two-pointer approach. The user is prompted to enter the input string in the main function. Subsequently, the main function calls the reverseString function and prints the reversed string.

Reverse a string without using the library function

If you want to reverse a string in C using function, you must first determine the string’s length. Subsequently, you need to run a for loop to allocate characters of another string equal to the characters of the entered string in reverse order. The part of this program that uses for loop will resemble the program that reverse a string in C using for loop. 

#include <stdio.h>
 
int main() 
{
 
char str1[50]="education", reversed[50];
int a, b, cnt = 0;
 
//original string
 
printf("\n The given string is %s", str1);
 
// loop to calculate the length of the string
while (str1[cnt] != '\0') {
  cnt++;
}
 
b = cnt - 1;
 
//assigning the value to characters of a new string
for (a = 0; a < cnt; a++) {
  reversed[a] = str1[b];
  b--;
}
 
printf("\n The reversed string is %s", reversed);
}

Output:

The given string is education
 The reversed string is noitacude

First, we calculate the length of the entered string and initialize an empty string. Subsequently, the program assigns all the character values of the entered string to that of the new string in the reverse sequence. The iteration continues till the determined length of the string.

Reverse a string using the recursion function

Using the recursion function to reverse a string in C makes the code more efficient. This function substitutes the basic iteration, but the swapping technique stays the same. The following program recursively calls the function containing logic. Moreover, each character is swapped. 

#include <stdio.h>
 
void reverseString(char* strg) 
{
if (*strg) 
{
        reverseString(strg + 1);
        printf("%c", *strg);
}
}
 
int main() 
{
char strg[50];
 
    printf("Please enter a string: ");
    fgets(strg, sizeof(strg), stdin);
 
// Discards the trailing newline character
if (strg[strlen(strg) - 1] == '\n') 
{
        strg[strlen(strg) - 1] = '\0';
}
 
    printf("The reversed string is: ");
    reverseString(strg);
    printf("\n");
 
return 0;
}

Output:

Please enter a string: English
The reversed string is: hsilgnE

The reverseString function in the above program recursively checks if the current character (*str) is not the null terminator (i.e. \0') If it’s not null, it calls itself with the subsequent character (str + 1) and prints the current character. The recursive function processes the string in reverse order and displays the reversed string at the output.

The main function requests the user to enter a string through fgets. Subsequently, it calls the reverseString function to reverse the string.

Reverse a string using for loop

This method involves reversing the characters’ orders in an input string using a for loop in C. Here’s an example program.

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

void reverseyourString(char* strg) 
{
    int length = strlen(strg);
    int a, b;
    char temp;
    
    for (a = 0, b = length - 1; a < b; a++, b--) 
{
        // Swap characters at positions a and b
        temp = strg[a];
        strg[a] = strg[b];
        strg[b] = temp;
    }
}

int main() 
{
    char strg[100];
    
    printf("Please enter a string: ");
    scanf("%s", strg);
    
    reverseyourString(strg);
    
    printf("Reversed string is: %s\n", strg);
    
    return 0;
}

Output:

Please enter a string: College
Reversed string is: egelloC

In this code, we have used a function called reverseyourString that accepts a character array (string) as input and then reverses it using a for loop. This loop begins from both ends of the string and swaps each character at corresponding positions until the central one is reached. Lastly, the program prints the reversed string in the main function.

Reverse a string using a while loop

Here’s an example program that uses a while loop to reverse an input string.

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

void reverseyourString(char* strg) 
{
int length = strlen(strg);
int first= 0;
int last = length - 1;
char tem;

while (first < last) 
{
// Swaps characters at positions first and last
tem = strg[first];
strg[first] = strg[last];
strg[last] = tem;

// Moves the first and last indices nearer to the middle
first++;
last--;
}
}

int main() {
char strg[100];

printf("Please enter a string: ");
scanf("%s", strg);

reverseyourString(strg);

printf("Reversed string is: %s\n", strg);

return 0;
}

Output:

Please enter a string: Study
Reversed string is: ydutS

In this program, the reverseyourString function accepts a character array as input. It initializes a first variable to 0 (the string’s beginning) and a last variable to length - 1 (the string’s end). 

In the while loop, the defined function swaps the characters at first and last using a tem variable. Subsequently, it increments first and decrements last to move nearer to the center of the string. The while loop continues until the first becomes greater than or equal to the last.

The user is prompted to enter a string in the main function. This is then passed to reverseyourstring function. Lastly, the printf function prints the reversed string as the output.

Reverse a string using pointers

The reverseString function in the below program reverses the input string strng using two pointers: begin and end. The begin pointer first points to the string’s first character, whereas the end pointer is moved to the last character of the string. This is done by repeating until it reaches the null terminator ('\0').  The program performs character-by-character swapping.

Next, the function uses two pointers to reverse the string by swapping each character. The begin pointer is incremented, and the end pointer is decremented until they run into the center of the string.

The main function allows the user to enter a string through fgets function. Subsequently, it calls the  reverseString function to perform string reversal.

#include <stdio.h>
 
void reverseString(char* strng) 
{
char* begin = strng;
char* end = strng;
 
// The following while loop moves the end pointer to the termination of the string
while (*end) 
{
        end++;
}
end--;
 
// The following while loop reverses the string by swapping characters
while (begin < end) 
{
        char temp = *begin;
        *begin = *end;
        *end = temp;
 
        begin++;
        end--;
}
}
 
int main() 
{
char strng[50];
 
    printf("Please enter a string: ");
    fgets(strng, sizeof(strng), stdin);
 
// The below loop discards the trailing newline character
if (strng[strlen(strng) - 1] == '\n') 
{
        strng[strlen(strng) - 1] = '\0';
}
 
    reverseString(strng);
 
printf("The reversed string is: %s\n", strng);
 
return 0;
}

Output:

Please enter a string: learn
The reversed string is: nrael

Reverse a String Using Another String

Here’s the program:

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

void reverseaString(const char* strg, char* reversed) 
{
int length = strlen(strg);
int m, n;

// Copies each character from strg to reversed in reverse order
for (m = length - 1, n = 0; m >= 0; m--, n++) 
{
reversed[n] = strg[m];
}

// Adds null terminator to the termination of reversed string
reversed[length] = '\0';
}

int main() 
{
char strg[100];
char reversed[100];

printf("Please enter a string: ");
scanf("%s", strg);

reverseaString(strg, reversed);

printf("Reversed string is: %s\n", reversed);

return 0;
}

Output:

Please enter a string: Education
Reversed string is: noitacudE

In the above code, reverseaString function accepts two parameters: strg and reversed. We’ve used a for loop to iterate on the input string’s characters in reverse order. In the main function, the program prompts the user to enter a string. It is subsequently passed with the reversed string to the reverseaString function. Finally, the reversed array stores the reversed string and prints it at the output.

Reverse a String by Displaying It in Reverse Order

Here’s an example program to reverse an input string by displaying it in reverse order. 

#include <stdio.h>
#include <string.h>
 
int main() 
{
char strng[50];
 
    printf("Please enter a string: ");
    fgets(strng, sizeof(strng), stdin);
 
// The below loop discards the trailing newline character
if (strng[strlen(strng) - 1] == '\n') 
{
        strng[strlen(strng) - 1] = '\0';
}
 
    printf("The reversed string is: ");
 
// The following loop displays the string in the reverse order
for (int x = strlen(strng) - 1; x >= 0; x--) 
{
        printf("%c", strng[x]);
}
 
    printf("\n");
 
return 0;
}

Output:

Please enter a string: Technology
The reversed string is: ygolonhceT

In the above program, the main function lets the user input a string through the fgets function. It subsequently iterates over the characters of the string in reverse sequence. Specifically, it begins with the last character (strlen(str) - 1) and ends with the first character (0). 

Conclusion

The string reversal capability in C helps in encryption, palindrome, etc. The most common method to reverse your string in C is the swapping technique. Moreover, string reversal allows you to search and sort by the end of strings.

Tutorials are certainly one of the best approaches to strengthening your fundamentals in C. In addition to going through the tutorial, mastering the latest technical skills is also a vital facet that aspirants must consider, and this is what upGrad assists with!

Along with getting familiar with the string reversal methods in C, check out upGrad’s Master of Science in Computer Science Program by Liverpool John Moores University to significantly enhance your career graph in the tech industry!

FAQs

1. Can you reverse a string without altering the original string?

You can reverse a string in C without altering the original string by defining a new string and copying the characters in the reverse order.

2. Is it possible to reverse a string in C using library functions?

String reversal in C is possible using library functions. The strrev function from the <string.h> library is useful for the same. But you must take into account that the strrev function doesn’t belong to the C standard library, and it might not be available on all compilers or systems.

3. What is the time complexity and space complexity of reversing a string in C? Explain with reasons for each.

The time complexity of reversing a string in C is O(n) (where n is the string’s length). The reason is you have to iterate over each character of the string once to accomplish reversal. The space complexity of reversing a string in C is O(1). The reason is the reversal is performed in-place, and additional memory is not required. The additional memory is required only when using a separate string to save the reversed output.

Leave a Reply

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