将“I am from China”倒置为“China from am I”
版本一
#include <stdio.h>
int main()
{
int i=0;
char word[255][255];
while(scanf("%s",word[i++])&&(getchar()!='\n'));
while(--i)
printf("%s ",word[i]);
printf("%s",word[0]);
return 0;
}
输入:I am from China!
输出:China! from am I
版本二:
#include <stdio.h>
#define SIZE 255
void reorder(char *s)
{
char *p1 = s,*p2;
int i = 0,count = 0;
while( (*p1) != '\0')
{
p1++;
count++; //计算一整串字符串的长度
}
p1--; //指向字符串的最后一个字符
while(count > 0)
{
while( (*p1) != ' ' && count >0)
//从字符串的最后一个字符往回找单词,并记录单词的长度
{
p1--;
i++;
count--;
}
p2 = p1+1;
//指向查找出来的单词的首个字符
while( i > 0)
{
putchar(*p2); //顺序打印单词
p2++;
i--;
}
if( (*p1) == ' ')
//打印遇到的空格符,并将指针指向前一个字符,寻找非空格字符
{
putchar(*p1);
p1--;
count --;
}
}
return ;
}
int main()
{
char str[SIZE] = "I am from China";
printf("%s\n",str);
reorder(str);
printf("\n");
return 0;
}
输出结果: