این یک مثال تقریبا کاملی است امتحانش کنید :
#include <iostream>
#include <string>
using namespace std;
void printReverse(const string& s)
{
for (int i = s.length() - 1; i >= 0; --i) cout << s[i];
}
// the original string is reversed ...
// note: C++ strings are mutable ... i.e. can be modified (in place)
void reverse(string& s)
{
int begin = 0, end = s.length() - 1;
char tmp;
while (begin < end) // swap begin and end ... char's
{
tmp = s[begin];
s[begin++] = s[end];
s[end--] = tmp;
}
}
// a new local copy of a string is reversed
string getReverse(string s)
{
int begin = 0, end = s.length() - 1;
char tmp;
while (begin < end) // swap begin and end ... char's
{
tmp = s[begin];
s[begin++] = s[end];
s[end--] = tmp;
}
return s; // returns a new copy of this reversed copy
}
int main()
{
// 0 //
string testStr = "abcdefghijklmnopqrstuvwxyz";
cout << "(0) Original string: " << testStr << endl;
// 1 //
cout << "\n(1) After calling printReverse(testStr): ";
printReverse(testStr);
cout << endl;
// 2 //
// note: C++ strings are mutable ...
reverse(testStr);
cout << "\n(2) After calling reverse(testStr): " << testStr
<< "\nThe original string is now reversed ..." << endl;
// 3 //
cout << "\n(3) After calling getReverse(testStr): " << getReverse(testStr)
<< "\nThe new (temporary) copy is reversed ..."
<< "\nbut the string passed in is still: " << testStr << endl;
// 4 //
cout << "\n(4) Or using reverse_iterator to print reversed: ";
string::reverse_iterator rit = testStr.rbegin();
string::reverse_iterator rit_end = testStr.rend();
while (rit != rit_end) { cout << *rit; ++rit; }
cout << "\nbut the string is still: " << testStr << endl;
// 5 //
cout << "\n(5) Or using const_reverse_iterator to print ... ";
string::const_reverse_iterator crit = testStr.rbegin();
string::const_reverse_iterator crit_end = testStr.rend();
while (crit != crit_end) { cout << *crit; ++crit; }
cout << "\nbut the string is still: " << testStr << endl;
cout << "\nPress 'Enter' to continue ... " << flush;
cin.get();
}