输入一句话,然后把这个字符串以单词为单位,逆转输出,比如将“Alice call Jack”转换为“Jack call Alice”,实现速度最快,移动最少。
#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
int main(void) {
string ret;
int i = 0;
int n = 0;
cout << "请输入一串数字" << endl;
getline(cin, ret);
while (ret[i])
{
while (ret[i] == ' ')i++;//跳过前面的空格,ret[i]是下一个单词的第一个字母
int j = i;
while (ret[j]&& ret[j]!=' ')j++;//ret[j-1]是单词的最后一个字母
//逆转单词
for(int k1=i, k2=j-1;k1<k2;k1++,k2--)
{
char temp =ret[k1];
ret[k1] = ret[k2];
ret[k2] = temp;
}
i = j;
}
for (int i =ret.length(); i >= 0; i--)
{
cout << ret[i];
}
system("pause");
return 0;
}