V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
spencerqiu
V2EX  ›  问与答

C 艹 字符串问题求解

  •  
  •   spencerqiu · 2014-10-21 11:32:56 +08:00 · 2300 次点击
    这是一个创建于 3477 天前的主题,其中的信息可能已经有所发展或是发生改变。
    题目描述 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 条回复    2014-10-21 12:59:03 +08:00
    timonwong
        1
    timonwong  
       2014-10-21 11:50:12 +08:00
    方法很多种

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

    reverse_copy(words.begin(), words.end(), ostream_iterator<string>(cout, " "));
    Exin
        2
    Exin  
       2014-10-21 12:04:21 +08:00
    这个是用到了栈(Stack)的概念
    可以弄一个String的数组,从0位置(底部)开始遇到空格就保存一个单词
    然后到句末就从String数组顶部逐个输出,最后加不加空格看具体题目的情况而定
    jakwings
        3
    jakwings  
       2014-10-21 12:45:39 +08:00
    提供一种面对对象的方法:
    https://gist.github.com/jakwings/4f9d16b4e32c953ba8e1
    TMBest
        4
    TMBest  
       2014-10-21 12:55:03 +08:00 via Android   ❤️ 1
    1,先将整个字符串翻转
    2,将每个单词翻转
    jakwings
        5
    jakwings  
       2014-10-21 12:59:03 +08:00
    @jakwings 哎,我顺序弄错了,回去面壁。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1216 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:58 · PVG 01:58 · LAX 10:58 · JFK 13:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.