1009 說反話 (20 分)
給定一句英語,要求你編寫程序,將句中所有單詞的順序顛倒輸出。
輸入格式:
測試輸入包含一個測試用例,在一行內給出總長度不超過 80 的字符串。字符串由若干單詞和若干空格組成,其中單詞是由英文字母(大小寫有區分)組成的字符串,單詞之間用 1 個空格分開,輸入保證句子末尾沒有多餘的空格。
輸出格式:
每個測試用例的輸出佔一行,輸出倒序後的句子。
輸入樣例:
Hello World Here I Come
輸出樣例:
Come I Here World Hello
代碼實現(給出三種方法):
方法一:中規中矩,用二維數組存放即接收輸入,直接從後往前輸出即可。
#include<stdio.h>
#include<string.h>
int main()
{
char str[81];
gets(str);
int len=strlen(str);
int row,col=0;
char ans[81][81];
for(int i=0;i<len;i++)
{
if(str[i]!=' ')
{
ans[row][col++]=str[i];
}
else
{
ans[row][col]='\0';
row++;
col=0;
}
}
for(int i=row;i>=0;i--)
{
printf("%s",ans[i]);
if(i>0)
{
printf(" ");
}
}
return 0;
}
方法二:同樣用二維數組,但在接收輸入時用while循環,兩行代碼解決,輸出同方法一。
#include<stdio.h>
int main()
{
int num=0;
char ans[90][90];
while(scanf("%s",ans[num])!=EOF)
{
num++;
}
for(int i=num-1;i>=0;i--)
{
printf("%s",ans[i]);
if(i>0)
{
printf(" ");
}
}
return 0;
}
方法三:要複雜些,但是可以學到東西,膜拜的大神代碼,很有意思
1、用fgets()函數接收字符串,講解在fgets()函數介紹
2、利用isspace()函數,移動指針到相應的目的地址,從而能控制輸出序列
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[81], *p = line, *i;
fgets(line, 81, stdin);
while(*++p); /* Go to the end of the string */
while(p > line) /* Will break at the beginning of the string */
{
while(isspace(*--p)) ; /* Find the end of a word */
while(p > line && !isspace(*(p - 1))) p--; /* Find start of the word */
for(i = p; *i && !isspace(*i); putchar(*i++)); /* Print the word */
putchar(p == line ? '\0' : ' '); /* print blankspace if not at end */
}
return 0;
}