句内单词反转

要求:将一个字符串在句内按单词反转,如将I am a student.反转后输出student. a am I

思路一:很容易观察到输出后的结果是在原字符串基础上按单词逆序输出,因此很容易想到用栈来实现,因为栈是用来先进后出的一种数据结构,因此我们可以将每个单词入栈,然后出栈即为结果。


思路二:可以考虑用反转函数来实现,即先将整个句子反转,然后再将每个单词反转。如:将原字符串反转后为:.tneduts a ma I,然后再将每个单词反转结果为:student. a am I即为所求结果。反转函数的实现很简单,关键是对句内单词的反转,即怎样才符合是一个单词。如果用pIndex字符指针指向当前处理字符,则当*pIndex!=' '&&*(pIndex+1)==' '时即满足当前子串为一个单词。具体可以参看我的博文统计字符串单词个数。基于此思路的代码如下:

#include<iostream>
using namespace std;
void reserve(char *pstr,int start,int end)
{
	while(pstr[start]!=''&&start<end)
	{
		swap(pstr[start],pstr[end]);
		start++;
		end--;
	}
}
void reserve(char *start,char *end)
{
	while(start<end)
	{
		swap(*start,*end);
		start++;
		end--;
	}
}//当考虑到要用指针来操作字符串的时候,反转函数最好写这一个,因为前面一个
//参数中要涉及到int型形参,这样不利于指针操作,或者说指针的灵活性不能体现
//出来。
void wordReserve(char *pStr)
{
	char *pStart=pStr;
	while(*pStr!='')
	{
		pStr++;
	}
	char *pEnd=pStr-1;//此处必须减1,因为while循环终止的条件是*pstr=''
	reserve(pStart,pEnd);//反转整个句子
	char *pIndex=pStart;
	char *start,*end,*temp;
	while(*pIndex)
	{
		if(*pIndex==' ')
		{
			pIndex++;
		}
		else
		{
			start=pIndex;
			while(*pIndex&&(*pIndex)!=' ')//用来判断是否为一个单词
			{
				pIndex++;
			}
			end=pIndex-1;//此处必须减1,因为while循环终止的条件是*pIndex=‘ ’
			reserve(start,end);//反转每个单词
		}
	}
}
void main()
{
	char str[]="I am a student.";
	wordReserve(str);
	cout<<str<<endl;
}
程序运行结果如下:


原文地址:https://www.cnblogs.com/hainange/p/6334094.html