A Journey 2 Eternity

Reverse a string with and without using array script

Posted on: June 28, 2012

void ReverseStringWithArrayScript(char* str)
{
  char* end = str;
  char tmp;
  int length = 0;

  if(str) {
    while (*end++) { // find the end of str and length
      ++length;
    }
    --end; // set one char back, since last char is null

    for(int i = 0, j = length - 1; i < (length / 2); i++, j--) {
      tmp = str[i];
      str[i] = str[j];
      str[j] = tmp;
    } // end for loop....
  } // end nullptr checking loop....
}

void ReverseString(char* str)
{
  char* end = str;
  char tmp;

  if(str) {
    while (*end) { // find the end of str
      ++end;
    }
    --end; // set one char back, since last char is null

    while (str < end) {
      tmp = *str;
      *str++ = *end;
      *end-- = tmp;
    } // end while loop....
  } // end nullptr checking loop....
}
Advertisements
Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Pages

Categories

June 2012
M T W T F S S
« Dec   Jul »
 123
45678910
11121314151617
18192021222324
252627282930  

Blog Stats

  • 27,085 hits
%d bloggers like this: