Reverse a string and reverse a sentence

/*
 *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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值