Results 1 to 7 of 7
Hybrid View
-
16th May 2008 18:28 #1Registered User
Join Date: Dec:2006
Location: SOFIA
Posts: 18
recursion { recursive helper function }
source code za C++/G++ linux dev C++ windows

hint Exercise P14.1 Exercise P14.1
http://www.horstmann.com/bigcpp/solu...14/ExP14_1.cpp
#include <string>
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();
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;
}
int main()
{
Sentence greeting("Hello!");
cout << greeting.reverse() << "\n";
return 0;
}
-
16th May 2008 18:46 #2
-
16th May 2008 18:55 #3
-
16th May 2008 19:14 #4
, .
, , .
-
16th May 2008 21:23 #5Registered User
Join Date: Dec:2006
Location: SOFIA
Posts: 18
-
16th May 2008 21:54 #6
/ . , ,
: XaMaB; . 0.42
In God we Trust (all others must submit a X.509 certificate). , ()
-
18th May 2008 15:17 #7Registered User
Join Date: Dec:2006
Location: SOFIA
Posts: 18

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; }Last edited by mibit; 18th May 2008 at 15:24.




Reply With Quote

Lenovo ThinkPad 15 IdeaPad 15
5th May 2023, 22:16 in