前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Text Reverse HDU - 1062 字符串处理,空格切分。

Text Reverse HDU - 1062 字符串处理,空格切分。

作者头像
种花家的奋斗兔
发布2020-11-13 14:13:27
3350
发布2020-11-13 14:13:27
举报

Text Reverse HDU - 1062

Ignatius likes to write words in reverse way. Given a single line of text which is written by Ignatius, you should reverse all the words and then output them.

Input

The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow. Each test case contains a single line with several words. There will be at most 1000 characters in a line.

Output

For each test case, you should output the text which is processed.

Sample Input

3 olleh !dlrow m'I morf .udh I ekil .mca

Sample Output

hello world! I'm from hdu. I like acm.

Hint

Remember to use getchar() to read '\n' after the interger T, then you may use gets() to read a line and process it.

该题目的意思就是说要字符串反转,也就是说对于用空格分开的每一个字符串,需要对这个单独的字符串执行反转操作,这是我最初的理解,即每个字符串中间有一个空格,但是,事实上,这并不一定是符合正确格式的句子,所以,字符串之间的空格数量不一定为1;也就是说字符串和字符串之间可能有多个空格,同时,在整个字符串的最后,可能还有一大堆空格,所以,不能简单地使用库函数中的字符串分割函数,如下:

	string str;
    	getline(cin,str);
    	int cnt=0;
    	for(int i=0;i<str.size();i++)
    	{
    		if(str[i]==' ')
    		{
    			cnt++;
			}
		}
		string s[cnt+1];
		istringstream is(str);//根据空格切分为多个字符串
   		for(int i=0;i<cnt+1;i++)
   		{
   			is>>s[i];
   			reverse(s[i].begin(),s[i].end());
		}
		for(int i=0;i<cnt+1;i++)
		{
			cout<<s[i];
			if(i!=cnt)
				cout<<" ";
		 }
		cout<<endl;		

很显然,这样想的太简单了,wrong answer

然后呢,就只能正常的做这个题目了,AC代码如下:

#include <iostream>
#include <cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include <sstream>

using namespace std;

int main()
{
	int n;
	cin >> n;
	int temp = getchar();
	while (n--)
	{
		string str;
		getline(cin, str);
		int i = 0;
		int flag[1000];
		memset(flag, 0, sizeof flag);
		while (i < str.size())
		{
			if (str[i] == ' ')
			{
				flag[i] = 1;
			}
			i++;
		}
		int start = 0;
		i = 0;
		while (i < str.size())
		{
			if (flag[i] == 1)
			{
				for (int j = i - 1; j >= start; j--)
				{
					cout << str[j];
				}
				start = i + 1;
				cout << ' ';
			}
			if (i == str.size()-1)
			{
				for (int j = i; j >= start; j--)
				{
					cout << str[j];
				}
			}
			i++;
		}
		cout << endl;
	}
	return 0;
}

重点:cin在读入数据之后,会停留在行末进行等待,这时候,如果使用getline,等读入时,读入的是换行符,而不是下一行字符,当然,这也是cin读入数据比较慢的原因,没读完一行数据,就要等待,而不是直接进入下一行读取。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-03-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Text Reverse HDU - 1062
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档