Reverse words in a given string | GeeksforGeeks
The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple space in between.
翻转句子中单词的顺序
Read full article from Reverse words in a given string | GeeksforGeeks
/*Function to reverse words*/
void
reverseWords(
char
*s)
{
char
*word_begin = s;
char
*temp = s;
/* temp is for word boundry */
/*STEP 1 of the above algorithm */
while
( *temp )
{
temp++;
if
(*temp ==
'\0'
)
{
reverse(word_begin, temp-1);
}
else
if
(*temp ==
' '
)
{
reverse(word_begin, temp-1);
word_begin = temp+1;
}
}
/* End of while */
/*STEP 2 of the above algorithm */
reverse(s, temp-1);
}
void
reverse(
char
*begin,
char
*end)
{
char
temp;
while
(begin < end)
{
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
The above code doesn’t handle the cases when the string starts with space. The following version handles this specific case and doesn’t make unnecessary calls to reverse function in the case of multiple space in between.
void
reverseWords(
char
*s)
{
char
*word_begin = NULL;
char
*temp = s;
/* temp is for word boundry */
/*STEP 1 of the above algorithm */
while
( *temp )
{
/*This condition is to make sure that the string start with
valid character (not space) only*/
if
(( word_begin == NULL ) && (*temp !=
' '
) )
{
word_begin=temp;
}
if
(word_begin && ((*(temp+1) ==
' '
) || (*(temp+1) ==
'\0'
)))
{
reverse(word_begin, temp);
word_begin = NULL;
}
temp++;
}
/* End of while */
/*STEP 2 of the above algorithm */
reverse(s, temp-1);
}
Read full article from Reverse words in a given string | GeeksforGeeks