C语言:字符串空格单词形式的反转

eg : 输入 Are you pig? 输出 pig? you Are
第一种方法:全部取反,检测到’ ’ 在把之前的在反转

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

void Reverse(char *s)
{
	int i, length = strlen(s);
	char *end = s + length - 1;
	char ch;

	for(i = 0; i < length / 2; i++)
	{
		ch = *s;
		*s = *end;
		*end = ch;

		s++;
		end--;
	} 
}

void Reverse1(char *start, char *end)
{
	int i;
	int length = end - strart + 1;
	char ch;

	for(i = 0; i < length / 2; i++)
	{
		ch = *start;
		*start = *end;
		*end = ch;

	start++;
	end--;
	}
}

int main()
{
	char str[128] = {0};
	printf("请输入语句:\n");

	int i = 0;
	char ch;
	while((ch = getchar()) ! = '\n')
	{
		str[i++] == ch;
	}
	Reverse(str);
	char *start = str;
	char *end = str;
	
	while(*end =! '\0')
	{
		end++;
		if(*end == ' ')
		{
			Reverse1(start, end - 1);
			start = end + 1;
		}
	}
	Reversel(start, end -1); //字符串最后一个字符是'\0',还需要把最后反转

	printf("%s\n", str);
	return 0;
}

第二种方法:把’ ‘换成/0;指针从后向前移动,检测到’\0’就输出

#include<stdio.h>

int main()
{
	char str[128] = {0};
	int i = 0;
	char ch;

	while((ch =getchar()) != '\n')
	{
		str[i++] = ch;
	}

	char *start = str;
	while(*statr != '\0')
	{
		if(*start == ' ')
		{
			*start = '\0';
		}
		start++;
	}

	while(start != str)
	{
		start--;
		if(*start == '\0')
		{
			printf("%s", start +1);
		}
	}

	printf("%s\n",  start);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值