74.5k views
5 votes
g Write a method that accepts a String object as an argument and displays its contents backward. For instance, if the string argument is "gravity" the method should display -"ytivarg". Demonstrate the method in a program that asks the user to input a string and then passes it to the method.

User Xhirazi
by
5.8k points

1 Answer

5 votes

Answer:

The program written in C++ is as follows; (See Explanation Section for explanation)

#include <iostream>

using namespace std;

void revstring(string word)

{

string stringreverse = "";

for(int i = word.length() - 1; i>=0; i--)

{

stringreverse+=word[i];

}

cout<<stringreverse;

}

int main()

{

string user_input;

cout << "Enter a string: ";

getline (std::cin, user_input);

getstring(user_input);

return 0;

}

Step-by-step explanation:

The method starts here

void getstring(string word)

{

This line initializes a string variable to an empty string

string stringreverse = "";

This iteration iterates through the character of the user input from the last to the first

for(int i = word.length() - 1; i>=0; i--) {

stringreverse+=word[i];

}

This line prints the reversed string

cout<<stringreverse;

}

The main method starts here

int main()

{

This line declares a string variable for user input

string user_input;

This line prompts the user for input

cout << "Enter a string: ";

This line gets user input

getline (std::cin, user_input);

This line passes the input string to the method

revstring(user_input);

return 0;

}

User Abecker
by
6.3k points