Reverse a String in C++

What is String Reversal?

String reversal in C++ is the process of rearranging the characters of a given string in reverse order, changing the original order from end to start.

Example:

Original String: “programming”
Reversed String: “gnimmargorp”

Problem Description

Write a C++ program that takes a string and reverses it.

Problem Solution

1. The program takes a string.
2. Using a for loop and string function, the string is reversed.
3. The result is printed.
4. Exit.

There are different ways to reverse a string in C++. Let’s explore these methods to understand how to achieve string reversal in C++ effectively.

advertisement
advertisement
Method 1: Using For Loop

In this approach, we will utilize a for loop to reverse a string.

C++ Program/Source code

Here is the source code of C++ Program to Reverse a String. The program output is shown below.

/*
 * C++ Program to Reverse a String using For Loop
 */
 
#include<iostream>
#include<string.h>
using namespace std;
int main ()
{
    char str[50], temp;
    int i, j;
    cout << "Enter a string : ";
    gets(str);
    j = strlen(str) - 1;
    for (i = 0; i < j; i++,j--)
    {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
    cout << "\nReverse string : " << str;
    return 0;
}
Program Explanation

1. The user is asked to enter a string and it is stored in the character variable ‘str’.
2. The length of ‘str’ is stored in the variable ‘j’ and ‘i’ is initialized as 0.
3. Using a for loop, the string is reversed.
4. The ith character of str is swapped with jth character using a temporary variable ‘temp’.
5. The loop terminates when i is less than j.
6. str is then printed which is th result.

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

Time Complexity: O(N)
The time complexity of this C++ program is O(N), where N is the length of the input string. It uses a for loop to swap characters from both ends.

Space Complexity: O(1)
The space complexity is O(1) since it only uses a constant amount of extra space for the ‘temp’ variable, regardless of the input size.

Runtime Test Cases

Testcase 1: We enter the string “programming” to reverse it.

Enter a string : programming
Reverse string : gnimmargorp

Testcase 2: We enter the string “gubed” to reverse it.

advertisement
Enter a string : gubed
Reverse string : debug

Method 2: Using While Loop

In this approach, we will utilize a while loop to reverse a string.

C++ Program/Source code

Here is the source code of C++ Program to Reverse a String using while loop. The program output is shown below.

/*
 * C++ Program to Reverse a String using While Loop
 */
 
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    char str[50], temp;
    int i = 0, j;
    cout << "Enter a string : ";
    cin.getline(str, 50);
    j = strlen(str) - 1;
    while (i < j)
    {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
        i++;
        j--;
    }
    cout << "\nReverse string : " << str;
    return 0;
}
Program Explanation

1. The program reads a string from the user and stores it in a character array.
2. It initializes two pointers, i and j, to the beginning and end of the string, respectively.
3. The program uses a while loop to swap characters at positions i and j, moving towards the center until they meet.
4. The loop effectively reverses the string.
5. Finally, the program prints the reversed string as the output.

advertisement

Time Complexity: O(N)
The time complexity is O(N), where N is the length of the input string. The while loop iterates through half of the string (i.e., from 0 to N/2).

Space Complexity: O(1)
The space complexity is O(1) as it uses only a fixed amount of additional memory for variables that does not depend on the input size.

Runtime Test Cases

Testcase 1: We enter the string “MALAYALAM” to reverse it.

Enter a string : MALAYALAM
Reverse string : MALAYALAM

Testcase 2: We enter the string “CruisE” to reverse it.

Enter a string : CruisE
Reverse string : EsiurC

Method 3: Using Recursion

In this approach, we will utilize a recursive function to reverse a string.

Program/Source code
/*
 * C++ Program to Reverse a String using recursion
 */
 
#include <iostream>
#include <cstring>
using namespace std;
 
void reverseStringRecursive(char str[], int start, int end)
{
    if (start >= end)
        return;
    char temp = str[start];
    str[start] = str[end];
    str[end] = temp;
    reverseStringRecursive(str, start + 1, end - 1);
}
int main()
{
    char str[50];
    cout << "Enter a string : ";
    cin.getline(str, 50);
    int len = strlen(str);
    reverseStringRecursive(str, 0, len - 1);
    cout << "\nReverse string : " << str;
    return 0;
}
Program Explanation

1. The program defines a recursive function reverseStringRecursive to reverse a string, taking three arguments: str, start, and end.
2. The function swaps characters at start and end indices and recursively reverses the remaining part of the string.
3. In the main() function, the user inputs a string and calculates its length with strlen().
4. The reverseStringRecursive function is called with starting index 0 and ending index len – 1 (where len is the length of the string) to reverse the input string.
5. The reversed string is displayed as the output.

Time Complexity: O(N)
The time complexity of the program is O(N), where N is the length of the input string. The recursive function processes each character once.

Space Complexity: O(N)
The space complexity is O(N), due to the recursive function call stack that grows with the number of characters in the input string.

Runtime Test Cases

Testcase 1: We enter the string “hello world” to reverse it.

Enter a string : hello world
Reverse string : dlrow olleh

Testcase 2: We enter the string “racecar” to reverse it.

Enter a string : racecar
Reverse string : racecar

Method 4: Using Reverse Function

In this approach, we will use an in-built reversre function to reverse a string.

Program/Source code
/*
 * C++ Program to Reverse a String using Reverse Function
 */
 
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
 
int main()
{
    string input;
    cout << "Enter a string: ";
    getline(cin, input);
 
    // Using the inbuilt reverse() function to reverse the string
    reverse(input.begin(), input.end());
    cout << "Reversed string: " << input << endl;
    return 0;
}
Program Explanation

1. The program includes the necessary header files: <iostream>, <string>, and <algorithm>.
2. It prompts the user to input a string ans store it in string variable input.
3. The reverse() function from <algorithm> reverses the characters in the input string.
4. The program displays the reversed string using cout.
5. The program returns 0, indicating successful execution, and the user sees the reversed string as the output.

Time Complexity: O(N)
The time complexity is O(N), where N is the length of the input string. The reverse() function iterates through half of the string to reverse it.

Space Complexity: O(1)
The space complexity is O(1) because the program uses a constant amount of extra space, independent of the input size, and the reverse() function operates in-place without allocating additional memory.

Runtime Test Cases

Testcase 1: We enter the string “simple” to reverse it.

Enter a string : simple
Reverse string : elpmis

Testcase 2: We enter the string “racecar” to reverse it.

Enter a string : racecar
Reverse string : racecar

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 & discussions at Telegram SanfoundryClasses.