:: [intv] reverse a string ::
HOME


[Date Prev][Date Next][Date Index]

[intv] reverse a string


//Problem: Reverse a String
//Save as: main.cpp and compile as: g++ -o main main.cpp

#include <iostream>
#include <string.h> //required for strlen

using namespace std;

char * stringReverse(char *);


int main(){ char *str1 = "A Toyota! Race fast, safe car. A Toyota."; cout << str1 << " ** " << stringReverse(str1) << endl;

  char *str2 = "a";
  cout << str2 << " **  " << stringReverse(str2) << endl;

  char *str3 = "";
  cout << str3 << " **  " << stringReverse(str3) << endl;

}


char * stringReverse(char *a){ char *startIdx, *endIdx; char tmp;

  if (strlen(a) == 0) {return NULL;}
  if (strlen(a) == 1) {return a;}

  char *c;
  c = (char *)malloc(sizeof(char)*strlen(a));
  if (NULL == c) {cout << "ERROR" << endl;}

  c = strncpy(c, a, strlen(a));
  startIdx = c;
  endIdx = &c[strlen(c) - 1];

  while (startIdx < endIdx){
    tmp = *startIdx;
    *startIdx = *endIdx;
    *endIdx = tmp;
    startIdx++;
    endIdx--;
  }

  return c;
}


Comments and corrections are appreciated and can be sent to papers@mia.ece.uic.edu. Click here for ©opyright information.