Reverse a string and reverse a sentence

来源:互联网 发布:淘宝联盟付款订单失效 编辑:程序博客网 时间:2024/06/10 05:51
/* *Function: Reverse a sentence according to the certain delimitation. *Author: Tim *Date: 2013-10-25*/#include <string>#include <vector>#include <stack>#include <iostream>#include <algorithm> //include reverse();#include <sstream>using namespace std;int main(){//用STL库里的函数reverse()翻转字符串;string str = "I love you!";cout << "Original string: " << str << endl;reverse(str.begin(),str.end());cout << "After reversing, the string is: " << str << endl;/***翻转句子(以空格为分界符),示例:I am a   student! 反转后:student!   a am I,单词间的空格个数保持不变。***/stack<string> sta;string ss = "I  am  a   student!";istringstream f(ss);    string s;    while (getline(f, s, ' '))  // istream& getline (istream& is, string& str, char delim); {sta.push(s);sta.push(" ");}sta.pop(); //删除最终栈最外面的空格(多加的);cout << "-------------" << endl;cout << "Original sentence: " << ss << endl;cout << "After reversing: ";vector<string> rev;while(!sta.empty()){rev.push_back(sta.top());sta.pop();}for(vector<string>::iterator it = rev.begin(); it !=rev.end(); it++){cout << *it;}cout << endl;return 0;}


原创粉丝点击