以相反的顺序打印输入字符串字 [英] Printing input string words in reverse order

查看:247
本文介绍了以相反的顺序打印输入字符串字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用如果 ,而 / do - while ,我的工作是以相反的顺序打印以下用户的输入(字符串值)。



例如:



输入字符串值:您是美国人
以相反顺序输出:American are You



有办法吗?



我试过了

  string a; 
cout<< 输入字符串:;
getline(cin,a);
a = string(a.rbegin(),a.rend());
cout<< a<< endl
return 0;

...但这会颠倒单词而拼写不是我要去的。



如果和同时

解决方案

算法是:


  1. 颠倒整个字符串

  2. 颠倒单个字词



< 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:

  1. Reverse the whole string
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆