View Single Post
  #4 (permalink)  
Old 05-18-2008, 08:37 AM
mibit mibit is offline
Newbie
 
Join Date: May 2008
Posts: 7
Credits: 0
Rep Power: 0
mibit is on a distinguished road
Default Re: Help with recursion { recursive helper function }

See what I did Should I change anything ?
Code:
#include <string>
#include <iostream>
using namespace std;

/**
   Reverse a sentence.
*/
class Sentence
{
public:
   /**
      Creates a Sentence object.
      @param aPhrase a sentence to reverse.
   */
   Sentence(string aPhrase);
   
   /**
      Reverses this sentence.
      @return the reversed sentence
   */
   string reverse();
   string reverseSubstring(int beginning,int end);
     
private:
   string phrase;
};

Sentence::Sentence(string aPhrase)   
{
   phrase = aPhrase;
}

  
string Sentence::reverse()
{
   if (phrase != "")
   {
      string c = phrase.substr(0, 1);
      string rest = phrase.substr(1, phrase.length() - 1);
      Sentence tailSentence(rest);
      phrase = tailSentence.reverse() + c;
   }
   return phrase;
}
string Sentence::reverseSubstring(int beginning,int end)
{
   if (phrase != "")
   {
      string sBegining = phrase.substr(0, beginning - 1);
      string sEnd = phrase.substr(end,phrase.length()-1);
      Sentence toReverse(phrase.substr(beginning -1,end - 1));
      toReverse.reverse();
      phrase = sBegining + toReverse.phrase + sEnd;
   }
   return phrase;
}

int main()
{
   Sentence greeting("Hello!");
   //cout << greeting.reverse() << "\n";
   cout << greeting.reverseSubstring(2,4) << "\n";
   return 0;
}
Reply With Quote