以相反的顺序打印输入字符串字 [英] Printing input string words in reverse order
问题描述
使用如果
和 ,而
/ do
- while
,我的工作是以相反的顺序打印以下用户的输入(字符串值)。
例如:
输入字符串值:您是美国人
以相反顺序输出:American are You
有办法吗?
我试过了
string a;
cout<< 输入字符串:;
getline(cin,a);
a = string(a.rbegin(),a.rend());
cout<< a<< endl
return 0;
...但这会颠倒单词和而拼写不是我要去的。
如果和同时
算法是:
- 颠倒整个字符串
- 颠倒单个字词
< pre class =lang-c prettyprint-override> #include< iostream>
#include< algorithm>
using namespace std;
string reverseWords(string a)
{
reverse(a.begin(),a.end());
int s = 0;
int i = 0;
while(i
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;
}
Using if
and while
/do
-while
, my job is to print following user's inputs (string value) in reverse order.
For example:
input string value : "You are American" output in reverse order : "American are You"
Is there any way to do this?
I have tried
string a;
cout << "enter a string: ";
getline(cin, a);
a = string ( a.rbegin(), a.rend() );
cout << a << endl;
return 0;
...but this would reverse the order of the words and spelling while spelling is not what I'm going for.
I also should be adding in if
and while
statements but do not have a clue how.
The algorithm is:
- Reverse the whole string
- Reverse the individual words
#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;
}
这篇关于以相反的顺序打印输入字符串字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!