-2

i want a program which reverse given string in the below format. Suppose if I input string as = "This is a boy" then i want output reverse sting as = "boya si ishT"

one more example Input string = "if a" Output String = "af i" please help. i have written below program but not working as expected.

char string[] = "This is a boy\0";
char reverse[100] = {0};
int start = 0;
int len = strlen(string)-1;
int space= 0;
bool flag = false;
int count = 0;
while(len >= 0)
{ 

    if(string[len] == ' '  )
    {
        len--;
        flag = true;

    }

    if(flag && (string[len-1])  == ' ')
    {
        reverse[start] = string[len];

        reverse[++start] = ' ' ;
        len--;
        start++;
        flag = false;
        continue;
    }
    reverse[start] = string[len];
    flag = false;
    start++;
    len--;
}
  • It isn't clear from your examples what transformation you want to apply to the string. I think you need to clarify that. – juanchopanza Mar 06 '16 at 06:21
  • I think the OP made a typo and the first example should transform to `yoba si s ihT`. The number of letters in the words in the results are maintained (4,2,1,3) but the letters are reverse. – Synetech May 05 '21 at 04:24

1 Answers1

0

Since you have the C++ tag

#include <string>
#include <algorithm>
#include <iostream>

std::string str = "This is a boy";
std::reverse(str.begin(), str.end());
std::cout << str;

or

char str[] = "This is a boy";
std::reverse(str, str + strlen(str));
Jts
  • 3,447
  • 1
  • 11
  • 14
  • That won't match the strange required output. Otherwise, it would be a [duplicate of this](http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c) – juanchopanza Mar 06 '16 at 06:02
  • My bad, I wanted to fix my example, but I'm confused. In his first ouput he joins the last 2 strings (and doesn't reverse them), while in his second output he splits the if word and doesn't join them? wut o.o – Jts Mar 06 '16 at 06:19
  • Right, I can't figure out the pattern, if there is one. So OP needs to clarify. – juanchopanza Mar 06 '16 at 06:20