Display String Backwards

Beginner

Introduction

In this lab, you will learn how to write a C++ program to display a given string backwards. There are multiple approaches to reverse a given string in C++. We will explore two different methods: using a custom reverse function that we will build ourselves, and using the inbuilt reverse function in C++.

Custom function to reverse a string

First, letโ€™s write a custom function to reverse a given string. This function will swap the first character with the last, then the second with the second-last, and so on until the entire string is reversed.

Create the reverseStr function and pass the string by reference. This way, we can modify the original string rather than returning a new one. The function will have a for loop that will swap characters on either side of the string, gradually working its way inwards until the entire string is reversed.

#include<iostream>
#include<string>
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]);
    }
}

Using inbuilt "reverse" function

C++ also provides an inbuilt function to reverse a string which is present in the <algorithm> header file. We can use the reverse() function by passing the start and end position of the string to be reversed.

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main() {
    string str = "hello";
    reverse(str.begin(), str.end());
    cout << str;
    return 0;
}

Testing the Program

Letโ€™s test the program using any of the above-mentioned methods. To do this, simply call the function that you just created or the inbuilt reverse() function. Pass the string that you want to reverse as an argument to the function.

#include<iostream>
#include<string>
#include<algorithm>
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 myString = "Hello World!"; //define a string to be reversed

    //Method 1
    cout << "REVERSED STRING USING CUSTOM FUNCTION:\n";
    reverseStr(myString); //calling the custom function to reverse the string
    cout << myString << endl;

    //Method 2
    cout << "\nREVERSED STRING USING INBUILT 'REVERSE' FUNCTION:\n";
    reverse(myString.begin(), myString.end()); //calling the inbuilt function to reverse the string
    cout << myString << endl;

    return 0;
}

Summary

In this lab, we have learned how to write a C++ program to display a given string backwards. We explored two different methods- using a custom function that we created ourselves and using the inbuilt reverse function in C++. We have also tested the program using both methods by calling the functions. Now you can reverse any string in no time!

Other Tutorials you may like