C++实现单词逆序输出

来源:互联网 发布:tf卡测试软件 编辑:程序博客网 时间:2024/05/08 04:37

C++编程实现单词逆序输出

要是用分段截取或者遍历的话也未免太无聊了

方法1

指针

通用性较强的方法,两次逆转,对整个字符串进行逆转,然后根据空格判断每一个单词再逆转

#include <iostream>#include <string>using namespace std;string s;void reverse(int begin,int end) {    while (begin < end) {        char temp = s[begin];        s[begin] = s[end];        s[end] = temp;        ++begin;        --end;    }}int main(){    getline(cin, s);    int len = s.length();    int begin = 0;    reverse(begin, len-1);    for (int i = 0; i < len; i++) {        if (s[i] != ' ') {            if (i > 0 && s[i - 1] == ' ') {                begin = i;            }            else if (i < len - 1 && s[i + 1] == ' ' || i == len - 1)                reverse(begin, i);        }    }    cout << s;    return 0;}

方法2

使用STL标准模板库

这种流类是个便捷的方式

C++中STL库实在有太多要学习的东西

在此立flag

#include<iostream>  #include<string>  #include<sstream>  #include<list>  using namespace std;int main(){    string line, word;    list<string> s1;    getline(cin, line);    istringstream stream(line);    while (stream >> word)    {        s1.push_front(word);    }    cout << endl;    for (list<string>::iterator it = s1.begin(); it != s1.end(); ++it)    {        cout << *it << " " << flush;    }    return 0;}
0 0
原创粉丝点击