Tuesday, 28 January 2014

Reverse a String

Here's a program to reverse a string. Although I'm not sure about the time complexity, this program has worked well

  1 #include<iostream> 
  2 using namespace std;
  3 int main() 
  4 { 
  5     char *a, *b,c; 
  6     int i,j; 
  7     cout<<"Enter: "; 
  8     a=new char[50]; 
  9     b=new char[50]; 
 10     cin>>a; 
 11     int l=strlen(a); 
 12      
 13     for(i=0,j=l-1;i<l-1,j>0,i<j;i++,j--) //Swap last and first characters
 14     { 
 15         c=a[i]; 
 16         a[i]=a[j]; 
 17         a[j]=c; 
 18     } 
 19     for(i=0;i<l;i++) 
 20         cout<<a[i]; 
 21     return 0;
 22 } 
     

No comments:

Post a Comment