V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
spencerqiu
V2EX  ›  问与答

C 艹 字符串问题求解

  •  
  •   spencerqiu · Oct 21, 2014 · 3082 views
    This topic created in 4206 days ago, the information mentioned may be changed or developed.
    题目描述 Description
    给出一个英语句子,希望你把句子里的单词顺序都翻转过来

    输入描述 Input Description
    输入包括一个英语句子。

    输出描述 Output Description
    按单词的顺序把单词倒序输出

    样例输入 Sample Input
    I love you

    样例输出 Sample Output
    you love I

    我的思路:
    因为以空格隔开,我就在每看到一个空格就记录一次数据,输出,然后把计数器清零,但是似乎跑下来不太对。

    代码:
    01 #include<iostream>
    02 #include<cstring>
    03 #include<cstdlib>
    04 using namespace std;
    05 int main()
    06 {
    07 string s;
    08 getline(cin,s);
    09 int n=s.length();
    10 int count=0;
    11 string tmp;
    12 for (int i=n-1;i>=0;i--)
    13 {
    14 if (s[i]==' ')
    15 {
    16 for (int i=count-2;i>=0;i--)
    17 cout <<tmp[i];
    18 cout <<" ";
    19 count=0;
    20 continue;
    21 }
    22 else
    23 {
    24 tmp[count]=s[i];
    25 cout <<tmp[count];
    26 count++;
    27 }
    28 }
    29 system("pause");
    30 return 0;
    31 }
    5 replies    2014-10-21 12:59:03 +08:00
    timonwong
        1
    timonwong  
       Oct 21, 2014
    方法很多种

    vector<string> words{istream_iterator<string>{istringstream(s)},
    istream_iterator<string>{}};

    reverse_copy(words.begin(), words.end(), ostream_iterator<string>(cout, " "));
    Exin
        2
    Exin  
       Oct 21, 2014
    这个是用到了栈(Stack)的概念
    可以弄一个String的数组,从0位置(底部)开始遇到空格就保存一个单词
    然后到句末就从String数组顶部逐个输出,最后加不加空格看具体题目的情况而定
    jakwings
        3
    jakwings  
       Oct 21, 2014
    提供一种面对对象的方法:
    https://gist.github.com/jakwings/4f9d16b4e32c953ba8e1
    TMBest
        4
    TMBest  
       Oct 21, 2014 via Android   ❤️ 1
    1,先将整个字符串翻转
    2,将每个单词翻转
    jakwings
        5
    jakwings  
       Oct 21, 2014
    @jakwings 哎,我顺序弄错了,回去面壁。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2786 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 15:41 · PVG 23:41 · LAX 08:41 · JFK 11:41
    ♥ Do have faith in what you're doing.