HDU ACM 1.2.3 Text Reverse

Text Reverse

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10139 Accepted Submission(s): 2741
 
Problem Description
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.
 
 
      
题目的难点在于如何读入保持整行的字符串,以及读入后字符串末端是'\0'还是'\n'等的处理。
字符串输入参考:
http://blog.csdn.net/qq_39459939/article/details/78912668
遇到一个问题,读入一行字符串使用cin.get(a,1000),完成第一行之后不触发,改成getline后正常。修改为
cin.get(a,1000).get()后也正常。
参考说明:

方法五:get()读入char[]

使用方法:

char str3[1024];
cin.get(str3,1024);//读入char数组

说明:get函数读入时需要考虑最后的换行符,也就是说,如果用get读入多行数据,要把'\n'另外读出来,一般使用cin.get(str,1024).get();来读入多组数据。

 
      
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

void TextReverse(char a[], int beg, int end)
{
	char temp;
	while (beg < end)
	{
		temp = a[beg];
		a[beg] = a[end];
		a[end] = temp;
		beg++;
		end--;
	}
}

void main()
{
	int n;
	cin >> n;
	getchar();

	for (int i = 0; i < n;i++)
	{
		char a[1000];
		cin.getline(a,1000);//此处使用cin.get(a,1000),完成第一行之后不触发,改成getline后正常

		for (int beg = 0, end = 1; a[end] != '\0' && '\0' != a[beg];)
		{
			while (' ' == a[beg] ) 
				beg++;

			end = beg + 1;
			while (' ' != a[end] && '\0' != a[end]) 
				end++;

			TextReverse(a, beg, end-1);
			if ('\0' == a[end])
				break;
			else
			{
				beg = end + 1;
				end = beg + 1;
			}
		}
		
		for (int j = 0; a[j]!= NULL;j++)
			cout << a[j];
		cout << endl;
	}
}


	

猜你喜欢

转载自blog.csdn.net/qq_39459939/article/details/79064115