Reverse a string in place. Use pointers rather than array indexing. - C++ Data Type

C++ examples for Data Type:char array

Description

Reverse a string in place. Use pointers rather than array indexing.

Demo Code

#include <iostream>
#include <cstring>
using namespace std;
void revstr(char *str);
int main() {/*from   w ww  . j  av a  2s .c  o m*/
   char str[] = "abcdefghijklmnopqrstuvwxyz";
   cout << "Original string: " << str << endl;
   revstr(str);
   cout << "Reversed string: " << str << endl;
   return 0;
}
void revstr(char *str) {
   char t;
   char *inc_p = str;
   char *dec_p = &str[strlen(str)-1];
   while(inc_p <= dec_p) {
      t = *inc_p;
      *inc_p++ = *dec_p;
      *dec_p-- = t;
   }
}

Result


Related Tutorials