Reversing a String

Reversing a String

Write a program that reverses a given string and displays the reversed string to the user.

Example

EntryPoint
tnioPyrtnE

Hint

There are many ways to solve this. You can create a new string and loop through the input strings characters and add them to the start of the new string using insert. However, a more optimized way to do this is looping through the input string in reverse, and usign += or push_back to add characters to the end of the new string.

You have to include <iostream> and <string>.

Use getline to avoid running into problems getting inputs with spaces.

Answer

#include <iostream>
#include <string>

int main() {
    std::string input;
    // Prompt user to enter a string
    std::cout << "Enter a string: ";
    std::getline(std::cin, input);

    // Create a new string and add characters to it by looping the original string from the back.
    std::string reverse;
    for (int i = input.length() - 1; i >= 0; --i) {
        reverse.push_back(input[i]);
    }

    // Output the reversed string
    std::cout << "The reversed string is: " << reverse << std::endl;
}

This program creates a new string and adds each character from the original string in reverse order using a for loop.

Questions