/*
*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;
}
Reverse a string and reverse a sentence
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.