首先将整个字符串进行倒置,然后将每一个单词进行倒置。
#include<iostream>
using namespace std;
int reverseWords(char *);
int reverseStr(char *, int, int);
int reverseWords(char *str)
{
int wordBegin = 0, wordEnd = 0, len = 0;
if (str == NULL || *str == '\0')
return 0;
len = strlen(str);
reverseStr(str, 0, len - 1);
while (wordEnd < len)
{
if (str[wordEnd] != ' ')
{
wordBegin = wordEnd;
while (str[wordEnd] != ' '&&str[wordEnd] != '\0'&&wordEnd < len)
wordEnd++;
wordEnd--;
reverseStr(str, wordBegin, wordEnd);
}
wordEnd++;
}
return 1;
}
int reverseStr(char *str, int begin, int end)
{
char tmp;
if (str == NULL)
return 0;
if (begin < end)
{
tmp = str[begin];
str[begin] = str[end];
str[end] = tmp;
reverseStr(str, begin + 1, end - 1);
}
return 1;
}
int main()
{
char s[] = "I am a student";
int ret = reverseWords(s);
cout << s;
getchar();
return 0;
}