码迷,mamicode.com
首页 > 其他好文 > 详细

单词反转

时间:2015-05-10 14:26:20      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

//把字符串“I am a student”反转成为“student a am I”,不借助任何库函数。
//基本原理:首先我们把待反转字符串整体反转,比如
//说“I am a student”反转为”tneduts a ma I”,然后再逐个单

//词反转,最后得到“student a am I”

#include<iostream>
using namespace std;
//求字符串的长度
int mystrlen(const char *dest)
{
	int len = 0;
	while(*dest++ !='\0')
		len++;
	return len;
}
//字符串的翻转
void reverse(char *dest,int first,int last)
{
	for(;first<last;++first,--last)
	{
		//可不用建立第三方变量进行交换:运用'^'属性进行交换
		char temp;
		temp = dest[first];
		dest[first] = dest[last];
		dest[last] = temp;
	}
}
char* word_reverse(char *dest)
{
	int len = mystrlen(dest);
	int first = 0;
	int last = 0;
	reverse(dest,0,len-1);
	for(int i=0;i<len;i++)
	{
		if(dest[i] == ' ')
		{
			last = i-1;
			// 对于只有一个字符的单词比如说(I)没有必要反转
			if(first<last)
				reverse(dest,first,last);
			first = i+1;// 记录下一个单词的开始位置
		}
		//这里还可以加一些特殊字符的处理比如‘!’‘,’‘.’
		//处理方法将起始位置向前移动:first = i+1;
		else if(dest[i] == ',' || dest[i] == '.' || dest[i] == '!')
			first = i+1;
	}
	return dest;
}
void main(void)
{
	char dest[] = "i am a student!!";
	cout<<"dest:"<<dest<<endl;
	word_reverse(dest);
	cout<<"reverse:"<<dest<<endl;
}

结果

技术分享


单词反转

标签:

原文地址:http://blog.csdn.net/chenmengmengx/article/details/45619593

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!