10-0. 说反话 (20)

给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。

输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。

输出格式:每个测试用例的输出占一行,输出倒序后的句子。

输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
	char test[81] = {0};
	gets(test);
	int len = strlen(test);
	char *s = test + len;
	int count = 0;

	while (1) {
		if (s == test) {
			printf("%s\n", s);
			break;
		}
		if (*s == ' ' && *(s + 1) != ' ') {
			*s = '\0';
			printf("%s ", s + 1);
			s--;
		} else {
			s--;
		}
	}
	
	return 0;
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
	char test[81] = {0};
	char ch;
	char enter = 0xa;  //回车
	int i = 0;         //字符串长度
	int flag = 0;      //空格标记
	int count = 0;     //单词数量
	while (1) {
		scanf("%c", &ch);
		if (ch == enter) {
			count++;
			break;
		}
		if (ch == ' ') {
			flag = 1;
		} else {
			if (flag == 1) {
				test[i++] = ' ';
				flag = 0;
				count++;
			}
			test[i++] = ch;
		}
	}

	int j = 0;
	char **str = (char**)malloc(sizeof(char*) * count);
	for (j = 0; j < count; j++) {
		str[j] = (char*)malloc(sizeof(char) * i);  //动态创建字符串数组
		//memset(str[j], 0, sizeof(char) * i);	//初始化字符串数组
	}

	int n = count;
	char *begin = test;
	while (count--) {  //逆序写入字符串数组
		for (j = 0; j < i; j++) {
			if (*begin == ' ') {
				begin++;
				break;
			}
			if (*begin == '\0') {
				break;
			};
			str[count][j] = *begin++;  //写入字符串数组
		}
	}

	for (i = 0; i < n; i++) {
		if (i > 0) printf(" ");
		printf("%s", str[i]);
	}
	printf("\n");

	return 0;	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值