Reverse a string and reverse a sentence

本文详细介绍了如何利用C++的STL库中的reverse()函数来翻转句子,并通过实例展示了翻转句子的过程。同时,文章还深入探讨了如何以空格为分界符翻转句子,确保单词间的空格个数保持不变。
/*
 *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;
}


Zhuo is a lovely boy, but unfortunately, he falls in love with TwoBee. One day he received a letter asking that “who is Zhuo’s true love” from TwoBee. Zhuo think it is a good chance to show his heart to TwoBee,so he write a program to process this sentence so that the sentence changes to ”Zhuo loves TwoBee very much”. TwoBee was impressed by Zhuo’s talented programming techniques deeply, and they lived a happy life. Now Zhuo want to promote this technology to most useful field, now let us to make the Zhuo’s dream come true. There are multiple test cases. The first line contains a string str without space and an integer n. (1 <= n <= 100) The next n lines each line begins with a string indicating the kind of operation to the string. Append: give a new string str1 without space, you should append the str1 after str. Insert: give an integer m and a new string str2, you should insert the str2 after the m-th letter in the str. Erase: give two integers s and t, you should delete the letter from s-th to t-th in the str. If the letter is out the length of the str, please output “Error!” and this operation is invalid. Reverse: you should reverse the str. The length of the string in the input will not large than 100. After each operation, you should output the str. 输入样例 who#does#Zhuo#love? 5 Erase 18 1 Erase 0 9 Append s#TwoBee! Insert 17 #very#much Reverse 输出样例 who#does#Zhuo#love Zhuo#love Zhuo#loves#TwoBee! Zhuo#loves#TwoBee#very#much! !hcum#yrev#eeBowT#sevol#ouhZ
最新发布
12-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值