1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
void reversePart( char word[], int first, int last )
{
while ( first < last ) swap( word[first++], word[last--] );
}
bool findWordLimits( char word[], int &p, int &q, int last ) // Find next word limits, starting at p
{ // Return via p and q and return true iff found word
while ( p <= last && word[p] == ' ' ) p++;
if ( p > last ) return false;
q = p + 1;
while ( q <= last && word[q] != ' ' ) q++;
q--;
return true;
}
void reverseSentence( char *In, char *Out )
{
strcpy( Out, In ); // Copy In into Out as a work array
int last = strlen( Out ) - 1;
int p = 0, q;
while ( findWordLimits( Out, p, q, last ) ) // Find next word
{
reversePart( Out, p, q ); // Reverse that word
p = q + 1;
}
reversePart( Out, 0, last ); // Now reverse the lot
} // Out should already be null-terminated from strcpy
int main()
{
char A[] = "this is hopeless";
char *B = new char[strlen(A)+1]; // Set size in calling program; it's easier
reverseSentence( A, B );
cout << A << '\n' << B << '\n';
delete [] B;
}
|