1. 程式人生 > >字串按詞反向輸出

字串按詞反向輸出

#include<stdio.h>
#include<string.h>
char * reverse(char *,int );
char *reverse1(char *a,int low,int high);
int main()
{
	//printf("請輸入要輸入的字串:");
	//char *a;
	//scanf("%s",&a);
	char a[] = " hello world baby!";
	int length = strlen(a),j=0,k;
	char *p;
	p = reverse(a,length);
	for(int i = 0;i < length;i++)
	{	
	while(p[i] == ' ')
	{
		k = i;
		reverse1(p,j,k-1);
		j = k+1;
		break;
	}
	
	}
	printf("%s\n",p);
	return 0;
}

char * reverse(char *a,int len)
{
	char temp;
	for(int i = 0;i<(len/2);i++)
	{
		temp = a[i];
		a[i] = a[len-i-1];
		a[len-i-1] = temp;
	}
	return a;
}

char *reverse1(char *a,int low,int high)
{
	char temp1;
	for(int i = low,j = 0;i<((low+high+1)/2);i++,j++)
	{
		temp1 = a[i];
		a[i] = a[high-j];
		a[high-j] = temp1;
		
	}
	return a;
}