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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <iostream>
#include <string>
using namespace std;
//A space has been found, the word between that space and the previous space must be reversed
void reverse_word (string &original_string_par, string &reversed_string_par, int space_position_par, int previous_space_position_par);
//The word has been reversed and added to the new string
int main ()
{
string original_string, reversed_string;
string s1 (" ");
int previous_space_position = 0, x = 0, space_position = 0;
cout << "Enter a string: ";
//Get the entire string the user has inputed
getline(cin, original_string);
//For the length of the string, do the following.
while (x < original_string.length())
{
//Check each value of the string and see if it is a space. if not then continue to next value.
// if it is then mark that position as space_position and reverse the word that is between that and the previous_space_position.
if (original_string.at(x) == ' ')
{
space_position = x;
reverse_word (original_string, reversed_string, space_position, previous_space_position);
//After a word has been reversed, the previous space position must be updated.
previous_space_position = space_position;
}
x++;
}
//The previous loop does not catch the last word unless the last value is a space. so this will reverse the last word of the string.
space_position = original_string.length();
reverse_word (original_string, reversed_string, space_position, previous_space_position);
cout << "Your reversed string is: " << reversed_string << endl;
return 0;
}
void reverse_word (string &original_string_par, string &reversed_string_par, int space_position_par, int previous_space_position_par)
{
//A special case must be made for the first space found as the first value is a letter and not a space. precious_space_position = 0 which is the position of a lettter.
if (previous_space_position_par == 0)
{
int x = 2;
reversed_string_par += original_string_par[space_position_par-1];
for (int i = 1; i < space_position_par; i++)
{
reversed_string_par += original_string_par[space_position_par - x];
x++;
}
}
//For all other cases take the letter right before the space found and add it to the string. got closer and closer to the previous_space_position until the starting letter is reached.
else
{
for (int i = space_position_par; i > previous_space_position_par; i--)
{
reversed_string_par += original_string_par[i - 1];
}
}
reversed_string_par += ' ';
}
|