面试题---单词翻转

对于这道题,首先要将整个字符串按照字母整个进行翻转,然后再单词内进行翻转,重点在与分割出单词来,设两个标志first和last分别表示单词的开始和结束位置,连续空格的第一个或单一的一个空格前一个位置是前一个单词的结尾,连续空格的最后一个空格的下一个位置是下一个单词的开始。

代码如下:

#include<iostream>
#include<string>
using namespace std;

class WordsReverse
{
public:
	WordsReverse(string* _words) : words(_words){}
	string* reverseWord();
private:
	string* words;	
};

string* WordsReverse::reverseWord()
{
	string str = "";
	string temp;
	int size = words->size() - 1;
	while(size >= 0)
	{
		temp = "";
		while(size >= 0 && words->at(size) != ' ')
		{
			temp = words->at(size) + temp;
			size--;
		}
		str += temp;
		temp = "";
		while(size >= 0 && words->at(size) == ' ')
		{
			str += ' ';
			size--;
		}
	}
	*words = str;
	return words;
}


int main()
{
	string str = "I am a student.";
	WordsReverse *ch = new WordsReverse(&str);
	cout<<*(ch->reverseWord())<<endl;
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值