翻转单词顺序 (20 分)

L1-5 翻转单词顺序 (20 分)

给定一个字符串,翻转该字符串,翻转时单词中的字符顺序不变。例如,如果字符串为"Hello World",则翻转后为"World Hello"。单词间以一个或多个空格分隔。注意,字符串开头和结尾都可能有多个空格。

输入格式:

输入可能包括多行。每行代表一个字符串,除了空格外,标点符号和普通字母一样处理。你可以认为一行的字符总数不会超过50000个,单词数不会超过600,每个单词的长度也不会超过30。

输出格式:

输出包括多行,每行对应输入的一行,为翻转后的字符串。

输入样例:

student. a am I

输出样例:

I am a student.
#include<iostream>
#include<cstring>
#include<list>
#include<string>
using namespace std;
int main()
{
	list<char> list1 ;
	char str[50000] ;
	while(cin.getline(str,50000))
	{
		int n = strlen(str) ;
		for(int i=n-1;i>=0;i--)
		{
			char c = str[i] ;
			char c1 = str[i-1] ;
			if(c==' ')
				printf(" ") ;
			else
				list1.push_back(c) ;
			if(c!=' '&&c1==' ')
			{
				list<char>::iterator it=list1.begin();
				list1.reverse() ;
				for(it=list1.begin();it!=list1.end();it++)
					printf("%c",*it) ;
				list1.clear() ;
			}
					
		}
		list1.reverse() ;
		list<char>::iterator it=list1.begin();
		for(it=list1.begin();it!=list1.end();it++)
			printf("%c",*it) ;
		printf("\n") ;
		list1.clear() ;
	}
	return 0 ;
}

对比: https://blog.csdn.net/qq_41591279/article/details/88604542

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值