实现字符串中单词顺序的逆置

比如 i love you 变换为you love i

#include "string"
#include "iostream"

using namespace std;

void ReverseWord(char* p, char* q)
{
	char temp=NULL;
	while(p<q)
	{
		temp=*p;
		*p=*q;
		*q=temp;
		p++;
		q--;
	}
}

void ReverseSentence(char *str)
{
	char *p=str;
	char* q=p;
	while ('\0'!=*q)
	{
		if (*q==' ')
		{
			ReverseWord(p,q-1);
			q++;
			p=q;
		}
		else
			q++;
	}
	//实现最后一个单词的逆反
	ReverseWord(p,q-1);
	//实现整个句子的逆反
	ReverseWord(str,q-1);

}

int main()
{
	char str[] = "i love you very much";
	cout << str << endl;

	ReverseSentence(str);

	cout << str << endl;	
	return 0;
}

你可能感兴趣的:(字符串)