fork download
  1. // Saliha Babar CS1A Chapter 10, #2, Page 588
  2. //
  3. /*****************************************************************************
  4.  * REVERSE STRING
  5.  * ____________________________________________________________________________
  6.  * This program accept strings up to n characters, and it will reverse the
  7.  * string.
  8.  *
  9.  * Reverse happens as the following
  10.  * "Saliha" will result in "ahilaS".
  11.  * ______________________________________________________________________________
  12.  * INPUT
  13.  * size : size of the array allocated for string
  14.  * word : string of n characters
  15.  *
  16.  * OUTPUT
  17.  * reverseArray : pointer for the reversed array
  18.  * ****************************************************************************/
  19. #include <iostream>
  20. #include <cstring>
  21. using namespace std;
  22.  
  23. char* BackwardString (char array[], int size);
  24.  
  25. int main() {
  26. const int SIZE = 51; // INPUT - size of the string
  27. char word[SIZE]; // INPUT - array of the characters
  28. int strLength; // Length of string
  29. char* reverseArray; // Pointer of reversed array
  30.  
  31. cout << "Enter any word up to " << SIZE - 1 << " characters long\n";
  32. cin.getline(word, SIZE);
  33.  
  34. cout <<"This is original string \"" << word << "\"\n";
  35.  
  36. // Check for printable characters
  37. strLength = strlen(word);
  38.  
  39. // Call the backward function and reverse the array
  40. reverseArray = BackwardString (word, strLength);
  41.  
  42. cout <<"This is reversed string \"" << reverseArray << "\"\n";
  43.  
  44. delete [] reverseArray;
  45.  
  46. return 0;
  47. }
  48.  
  49. char* BackwardString (char array[], int size)
  50. {
  51. // Create a new memory location for reversed array
  52. char* reverse;
  53. reverse = new char [size+1];
  54.  
  55. for (int i = 0; i < size ; i++)
  56. {
  57. reverse [size -1-i] = array[i] ;
  58. }
  59. reverse[size] = '\0';
  60. return reverse;
  61. }
  62.  
Success #stdin #stdout 0s 5288KB
stdin
Saliha Babar
stdout
Enter any word up to 50 characters long
This is original string "Saliha Babar"
This is reversed string "rabaB ahilaS"