Interview Questions
Reverse words in a string
Reverse words in a string.
View Solution
void reverseString(char *str, int x, int y)
{
while (x < y)
{
char tmp = str[x];
str[x] = str[y];
str[y] = tmp;
x++;
y--;
}
}
void reverseWords(char *str)
{
int i = 0;
int j = 0;
while (str[j] != '\0')
{
if (str[j] == ' ')
{
reverseString(str, i, j - 1);
i = j + 1;
}
j++;
}
reverseString(str, i, j - 1);
}