【中级】单词倒排/华为机试(C/C++)

题目描述

对字符串中的所有单词进行倒排。

说明:

1、每个单词是以26个大写或小写英文字母构成;

2、非构成单词的字符均视为单词间隔符;

3、要求倒排后的单词间隔符以一个空格表示;如果原字符串中相邻单词间有多个间隔符时,倒排转换后也只允许出现一个空格间隔符;

4、每个单词最长20个字母;

输入描述:

输入一行以空格来分隔的句子

输出描述:

输出句子的逆序

示例1

输入

I am a student

输出

student a am I

代码1:

//第三十一题 【中级】单词倒排
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
	string in_str;
	while (getline(cin, in_str))
	{
		vector<string>vOut;
		size_t ePosition, sPosition = in_str.length() - 1;
		size_t iLegth = sPosition;
		for (int i = 0; i < in_str.length(); i++)
		{
			if (!isalpha(in_str[i]))
			{
				in_str[i] = ' ';
			}
		}
		while ((ePosition = in_str.find_last_of(' ', sPosition)) != string::npos)
		{
			int lenght = sPosition - ePosition;
			if (lenght > 0)
			{
				vOut.push_back(in_str.substr(ePosition + 1, lenght));
			}
			if (ePosition != 0)
				sPosition = ePosition - 1;
			else
			{
				sPosition = 0;
				break;
			}
		}
		if (sPosition != 0)
			vOut.push_back(in_str.substr(0, sPosition + 1));
		else if (isalpha(in_str[sPosition]))
		{
			char ctemp= in_str[0];
			string temp; 
			temp = ctemp;
			vOut.push_back(temp);
		}   
		string sOut;
		int iMax = vOut.size() - 1;
		for (int i = 0; i < iMax; i++)
		{
            cout<<vOut[i].c_str()<<" ";
		}
		cout << vOut[iMax].c_str()<<endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值