最近在CODIA刷题遇到了这样的题目,看到大家都在用递归解题一点也不符合菜鸟的做题风范,我就按照自己的想法凑了一下答案,仅供参考。
题目描述
输入一句话(不含标点),其中包含多个单词并以空格分隔,请把这句话改为“倒装句”,即单词出现的顺序前后颠倒(注意是单词顺序不是字母顺序,单词之间有空格)。输出该“倒装句”。
输入描述
- 1≤单词数目≤20
- 单词长度≤10
列入输入字符串:what is wrong with you 输出为:you with wrong is what
#include <stdio.h>
#include <string.h>
void main()
{
char sentence[100];
int i, count=0, maxs = 1;
gets(sentence);
// scanf("%[^\n]", sentence);
for(i=0;i<strlen(sentence);i++)
{
if(sentence[i] != ' ' && count != -1)
{
count++;
if(count>10)
{
count = -1;
break;
}
}
else
{
maxs++;
count = 0;
}
}
if(maxs>20 || strlen(sentence)<0 || count==-1)
printf("The sentense word num is not satify the requirement or some word length is too long!\n");
else
{
int length = strlen(sentence);
int printindex = 0;
for(int j = length-1;j>=-1;j--)
{
if(sentence[j] == ' ' || j == -1)
{
printindex = j+1;
for(;printindex<length;printindex++)
{
printf("%c", sentence[printindex]);
}
printf(" ");
length = j;
}
}
}
}