use*_*749 0 c++ string reverse
使用if 和 while/do- while,我的工作是以相反的顺序打印以下用户的输入(字符串值).
例如:
输入字符串值:"你是美国人"以相反的顺序输出:"American are You"
有没有办法做到这一点?
我试过了
string a;
cout << "enter a string: ";
getline(cin, a);
a = string ( a.rbegin(), a.rend() );
cout << a << endl;
return 0;
Run Code Online (Sandbox Code Playgroud)
...但这会颠倒单词和拼写的顺序,而拼写不是我想要的.
我也应该加入if和while声明,但不知道如何.
算法是:
#include<iostream>
#include<algorithm>
using namespace std;
string reverseWords(string a)
{
reverse(a.begin(), a.end());
int s = 0;
int i = 0;
while(i < a.length())
{
if(a[i] == ' ')
{
reverse(a.begin() + s, a.begin() + i);
s = i + 1;
}
i++;
}
if(a[a.length() - 1] != ' ')
{
reverse(a.begin() + s, a.end());
}
return a;
}
Run Code Online (Sandbox Code Playgroud)