将一个句子按单词反序。比如 “My name is daydayup”,反序后变为 “daydayup is name My”。
算法:首先将整个字符串逆置,然后对每个单词求逆
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int SIZE = 100;
void swap(char &a, char &b)
{
char c = a;
a = b;
b = c;
}
void swap_str(char *c, int beg, int end)
{
for(int i = beg, j = end - 1; i <= j; i++, j--)
{
swap(c[i], c[j]);
}
}
void reserve(char *c, int beg, int end)
{
swap_str(c, beg, end);//首先将整个字符串逆置
int j = 0, newbeg = 0;
for(int i = beg; i <= end; i++)
{
if(c[i] == ' ' || i == end)
{
swap_str(c, newbeg, i);//每个单词逆置
newbeg = i+1;
}
}
}
int main()
{
char c[SIZE];
gets(c);
int len = strlen(c);
reserve(c, 0, len);
puts(c);
}