【练习】翻转句子中单词的顺序

/************************************************************************/
/*                 翻转句子中单词的顺序。
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。
例如输入“I am a student.”,则输出“student. a am I”。               
思路:
利用STL,不过如此解法,恐怕违背了出题者本意
给出一个准确答案链接http://www.cnblogs.com/youwang/archive/2011/03/05/1971900.html*/
/************************************************************************/

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void reverseSentence();
int main()
{
	reverseSentence();
	return 0;
}

void reverseSentence()
{

	cout<<"please input the sentence"<<endl;
	vector<string> sentence;
	string s;
	while (cin)
	{
		cin>>s;
		if (cin)
		{
			sentence.push_back(s);
		}
		

	}

	while(sentence.size()!=0)
	{
		s=sentence.back();
		sentence.pop_back();
		cout<<s<<" ";
	}


}

  符合题意的解法

#include <iostream>

using namespace std;
void reverseSentence(char *sentence);
void reverse(char* begin,char *end);
 int main()
 {
	 char sentence[16]="I am a student.";
	 reverseSentence(sentence);
	 
	 cout<<sentence<<endl;
	 return 0;
 }
void reverse(char* begin,char *end)
{
	if (NULL==begin||NULL==end)
	{
		return;
	}
	char temp;
	while(begin<end)
	{
		temp=*begin;
		*begin=*end;
		*end=temp;
		begin++;
		end--;
	}

}
 void reverseSentence(char *sentence)
 {
	 if (NULL==sentence)
	 {
		 return;
	 }
	 char *begin,*end;
	 begin=sentence;
	 end=sentence;
	 while(*end!='\0')
		 end++;
	 end--;
	 reverse(begin,end);

	 end=begin;
	 while(*begin!='\0')
	 {
		 while(*end!=' '&&*end!='\0')
			 end++;
		 end--;
		 reverse(begin,end);
		 if (*(end++)==' ')
		 {
			 end++;
		 }
		 if (*(end++)=='\0')
		 {
			 break;
		 }
		 begin=end;
	 }

	// end=begin;

 }

  

posted @ 2011-10-24 10:49  refazy  阅读(234)  评论(0编辑  收藏  举报