Hello word -> word Hello
#include <iostream>
void swap(char* a, char* b)
{
if (a == b)
return;
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
};
void reverseStr(char* str, int i, int j)
{
while (i < j)
{
swap(&str[i++], &str[j--]);
}
};
void reverseSentence(char* str)
{
reverseStr(str, 0, strlen(str) - 1);
int left = 0;
int right = 0;
int idx = 0;
while (true)
{
if (str[idx] == ' ' || str[idx] == '\0')
{
right = idx - 1;
reverseStr(str, left, right);
if (str[idx] == '\0')
return;
while (str[idx + 1] == ' ')
idx++;
left = idx + 1;
right = left;
}
idx++;
}
};
int main()
{
char str[] = "Hello world I love you";
printf("Original string: %s\n", str);
reverseSentence(str);
printf("Converted string: %s\n", str);
return 0;
};