OneBite.Dev - Coding blog in a bite size

Reverse A String In C++

Code snippet for how to Reverse A String In C++ with sample and detail explanation

Reversing a string in C++ is a common task that many programmers encounter. It is a staple exercise for beginners learning the language and it not only tests your string manipulation skills but also your understanding of the array data structure.

Code Snippet: Reverse A String In C++

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

void reverseStr(string& str)  
{  
    int n = str.length();

    for (int i = 0; i < n / 2; i++) 
        swap(str[i], str[n - i - 1]); 
}

int main()  
{
    string str = "ABCDEF"; 
    reverseStr(str); 
    cout << str;
    return 0;
}

Code Explanation for Reverse A String In C++

First of all, we included relevant headers i.e., ‘iostream’ that provides basic input and output services, and ‘bits/stdc++.h’ which includes most standard library files, so it’s useful to save time while coding. Our namespace is ‘std’; standard library’s components are included in this namespace.

The function reverseStr(string& str) accepts a string and it does not return any value. We utilize the ‘pass-by-reference’ procedure to modify the input string directly in the function so that the changes we make to the string persist even after the function’s execution halts.

Inside this function, we find the length of the string, n = str.length();.

Then we initiate a loop that commences from 0 and terminates when it is less than half of the length of the string, for (int i = 0; i < n / 2; i++).

In each iteration of the loop, we utilize the builtin function ‘swap’ to exchange the i-th character and the (n-i-1)-th character, effectively inverting the order of the characters, swap(str[i], str[n - i - 1]);.

Towards the end, in the main() function, we define a string str = "ABCDEF"; and call the reverseStr(str); function to reverse it. We then print out the reversed string by cout << str;.

As soon as the main() function reaches the return 0; statement, the program execution will cease.

c-plus-plus