实现功能要求:将“I am from shanghai ”倒置为“shanghai from an I”即将句子中的单词位置倒置,而不改变单词内部结构。
方法一:使用指针数组,进行址传递
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define SIZE 4
int main()
{
char *str[20] = {0};
int i;
for(i = 0;i < SIZE;i ++)
{
str[i] = (char *)malloc(sizeof(char)* 20);//动态分配内存
if(NULL == str[i])
{
printf("malloc error!\n");
} //动态分配内存的错误保护
scanf("%s",str[i]);
}
for(i = SIZE - 1;i>= 0;i --)//实现逆序输出
{
printf("%s ",str[i]);
}
return 0;
}
方法二:使用gets()完成终端上的键入操作(会有警告)
int main()
{
char *ptr = (char *)malloc(sizeof(char) * 200);
if(NULL == ptr)
{
printf("maloc error\n");
}
gets(ptr);
char *tmp = ptr;
while(*ptr != '\0')//将单词之间的空格替换为'\0'
{
if(*ptr == ' ')
*ptr = '\0';
ptr ++; //后移
}
ptr --;
while(ptr != tmp)//判断条件为逆序至第一个单词
{
if(*ptr == '\0' )
printf("%s ",ptr + 1);//一旦有'\0'就输出其后的下一个单词
ptr --;
}
printf("%s",tmp );//最后将第一个单词输出
return 0;
}
方法三:使用getchar()完成终端上的键入操作
int main()
{
char *ptr = (char *)malloc(sizeof(char) * 200);
if(NULL == ptr)
{
printf("malloc error!\n");
}
char c;
char *tmp = ptr;
while((c = getchar()) != '\n')//getchar()特点:回车符自动停止键入
{
*ptr ++ = c;
}
ptr = tmp;
while(*ptr != '\0')
{
if(*ptr == ' ')
*ptr = '\0';
ptr ++;
}
ptr --;
while(ptr != tmp)
{
if(*ptr == '\0')
printf("%s ",ptr + 1);
ptr --;
} //原理同方法二,无警告
printf("%s",tmp);
return 0;
}