Reverse string using recursion in c++

C++ program for Reverse string using recursion. Here more information.

// Include header file
#include <iostream>
#include <string>
using namespace std;
// Reverse string using recursion in C++
class ReverseString
{
	public:
		// This is reversing the string elements recursively
		string reverseText(string text, int location)
		{
			// Base condition to stop the recursion process
			if (location >= 0)
			{
				// Recursive function call
				return text[location]  +  
                  this->reverseText(text, location - 1);
			}
			// When no character remaining
			return "";
		}
	// This is handling the request process of reverse string elements
	string reverse(string text)
	{
		// Display given string elements
		cout << "Before Text : [" << text << "]" << endl;
		return this->reverseText(text, text.length() - 1);
	}
};
int main()
{
	ReverseString *task = new ReverseString();
	string text = "ABCDE";
	text = task->reverse(text);
	// After reverse	
	cout << "After Text  : [" << text << "]\n" << endl;
	text = task->reverse("654A321");
	// After reverse	
	cout << "After Text  : [" << text << "]\n" << endl;
	return 0;
}

Output

Before Text : [ABCDE]
After Text  : [EDCBA]

Before Text : [654A321]
After Text  : [123A456]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved