首页 > 代码库 > 将字符串中的每个单词顺序进行颠倒,单词还是原来的单词,字母顺序不发生变化

将字符串中的每个单词顺序进行颠倒,单词还是原来的单词,字母顺序不发生变化

/*测试数据: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;
}