將字串中的每個單詞順序進行顛倒,單詞還是原來的單詞,字母順序不發生變化

期待一片自己的藍天發表於2014-06-05
/*測試資料:Shen zhen is a beautiful city!*/
/*執行結果:city! beautiful a is zhen Shen*/
#include<stdio.h>
#define SIZE 1000

void reverse(char *low,char *high)/*接受兩個指標,將指標中間的內容倒置*/
{
	while (low < high){
		*low = *low^*high;
		*high = *low^*high;
		*low = *low^*high;
		++low;
		--high;
	}
}

void reverseWord(char *str)
{
	char *c = str, *e = str, *low, *high;
	while (*e != 0){
		++e;
	}
	reverse(c,--e);/*將整個字串倒置*/
	while (*c!=0){
		while (*c != 0 && *c == 32){
			++c;
		}
		low = c;/*指向單詞首部的指標*/
		while (*c != 0 && *c != 32){
			++c;
		}
		high = c - 1;/*指向單詞尾部的指標*/
		if (low < high){
			reverse(low,high);/*將單詞倒置*/
		}
	}
	puts(str);
}

int main()
{
	char str[SIZE];
	printf("Please enter a string :\n");
	gets(str);
	reverseWord(str);
	return 0;
}

相關文章