題目
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
The program must switch the text lines in a backward order and split them by the middle, processing the input lines in pairs. If an empty or blank line is found, it is considered as a line but it is not printed out to the output.
Input
The input will be a text file with text lines.
Output
Standard output with the switched and splitted lines.
Sample Input
This lines must be printed backwards and splitted in the middle.
And each line too!
hellow my friend
how are you today
i hope you're fine
be cool, be nice.
Sample Output
hcae dnA!oot enil
wkcab detnirp eb tsum senil sihT.elddim eht ni dettilps dna sdra
y era wohyadot uo
m wollehdneirf y
oy epoh ienif er'u
,looc eb.ecin eb
思路
題目要求每一行從中間分開行數據,然后前后兩部分分別逆序,所以可以預先自定義一個部分逆序的函數,根據索引來進行逆序。
然后又要求成對處理行,所以每次掃入可以先掃入第一行,如果第一行能夠掃描進去了,那么就說明存在第二行了,也掃描進去。
因為題目要求對空行也進行掃入,所以要用gets(char* str)
函數進行讀入。
代碼
// Problem#: 1323
// Submission#: 2661187
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include<stdio.h>
#include<string.h>
// sicily doesn't support the strrev function in <string.h>, thus rewrites.
char* strrev(char *str) {
char *h = str, *t = str, ch;
while (*t++) {}
t--;
t--;
while (h < t) {
ch = *h;
*h++ = *t;
*t-- = ch;
}
return str;
}
void reverse(char* str) {
char tmp_str[10000 + 10];
int mid = strlen(str) / 2;
memset(tmp_str, 0, sizeof(tmp_str));
strrev(str);
strncpy(tmp_str, str, mid*sizeof(char));
strrev(str);
if ((strlen(str) % 2)) mid++;
str[mid] = 0;
strrev(str);
strcat(str, tmp_str);
}
bool checkEmptyLine(char* str) {
for (int i = 0; i < strlen(str); i++) {
if (str[i] != ' ')
return true;
}
return false;
}
int main() {
char str1[10000 + 10] = { 0 }, str2[10000 + 10] = { 0 };
while (gets(str1)) {
gets(str2);
if (str2[0] && checkEmptyLine(str2)) {
reverse(str2);
printf("%s\n", str2);
}
if (str1[0] && checkEmptyLine(str1)) {
reverse(str1);
printf("%s\n", str1);
}
memset(str1, 0, sizeof(str1));
memset(str2, 0, sizeof(str2));
}
return 0;
}