View Single Post
Old 10-23-2004, 01:14 PM   #1 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Reversing a string and palindromes.

I will present two forms:
- the STL way.
- the traditional way.

the STL way
Code:
 #include <iostream>
#include <string>
#include <algorithm>

using namespace std;

//Optional functions: depends on IDE. void wait_for_enter();

int main()
{
   string sOriginal("123321");
   string sReversed(sOriginal);

   reverse(sReversed.begin(), sReversed.end());
   cout<<sOriginal<<endl;
   cout<<sReversed<<endl;
   
   if(sOriginal == sReversed)
   {
      cout<<"Palindrome detected!"<<endl;
   }
   
   wait_for_enter();
   return 0;
}

//--------------------------------------------------- void wait_for_enter()
{
  cout << "press <enter> to continue...";
  // Reset failstate, just in case.
  cin.clear();
  string line;
  getline( cin, line);
}
the traditional way
Code:
 #include <iostream>
#include <string>

using namespace std;

//Optional functions: depends on IDE. void wait_for_enter();

int main()
{
   string sOriginal("123321");
   string sReversed;
   
   unsigned size = sOriginal.size();
   for(unsigned i=0; i < size; ++i)
   {
      //Traverse from sOriginal[5] to sOriginal[0] *IF* sOriginal.size() == 6.
      sReversed += sOriginal[size-i-1];
   }
   
   cout<<sOriginal<<endl;
   cout<<sReversed<<endl;
   
   if(sOriginal == sReversed)
   {
      cout<<"Palindrome detected!"<<endl;
   }
   
   wait_for_enter();
   return 0;
}

//--------------------------------------------------- void wait_for_enter()
{
  cout << "press <enter> to continue...";
  // Reset failstate, just in case.
  cin.clear();
  string line;
  getline( cin, line);
}
__________________
Valmont is offline   Reply With Quote