Wednesday, August 15, 2012

Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)


/*
Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
*/
#include <stdio.h>
void reverse(char* cStyleString) {
  char temp;
  char* leftSwap;
  char* rightSwap;
  leftSwap = cStyleString; // Position left swapping point at string's start
  rightSwap = cStyleString; // Position right swapping point at string's start
  while (*rightSwap) { // Repeat until terminating character (\0) is found
    rightSwap++; // Traverse string by advancing to the next character
  } // End of string now located
  rightSwap--; // Backtrack one step from terminating character
  while (leftSwap < rightSwap) {
    temp = *leftSwap; // Temporarily store character to swap
    *leftSwap = *rightSwap;
    *rightSwap = temp;
    leftSwap++; // Converge to centre of string
    rightSwap--; // Converge to centre of string
  }
}
int main() {
  char cStyleString[] = "Hello, world!";
  printf("%s\n", cStyleString);
  reverse(cStyleString);
  printf("%s\n", cStyleString);
  return 0;
}

No comments:

Post a Comment