现在的位置: 首页 > 综合 > 正文

【每日一题】2012.5.27:删除多余空格-非原创-方法2

2013年08月31日 ⁄ 综合 ⁄ 共 1202字 ⁄ 字号 评论关闭
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
void RemoveExtraSpace(char* str, int len)
{
	assert(len != 0);
	if(str == NULL)
	{
		return;
	}
	//当前已经处理好的结果字符串的尾指针
	char* result_tail = str;
	//顺序扫描字符串的每个字符的指针
	char* p = str;
	//存放p之前的字符是否是空格
	bool is_pre_space=false;
	//忽略字符串最前面的空格
	while (*p==' ' && len > 0)
	{
		p++;
		len--;
	}
	while (len > 0)
	{
		if (*p == ' ')//遇到空格
		{
			if (!is_pre_space)
			{
				//保留空格
				*result_tail = *p;
				result_tail++;
			}
			is_pre_space = true;
			p++;
			len--;
		}
		else if(*p == '\n')//遇到换行
		{
			//前面有空格
			if (is_pre_space)
			{
				result_tail--;
			}
			is_pre_space = false;
			//复制换行符
			*result_tail = *p;
			result_tail++;
			p++;
			len--;
			//忽略换行后的空格
			while (*p==' ' && len > 0)
			{
				p++;
				len--;
			}
		}
		else//其他字符
		{
			//复制换行符
			*result_tail = *p;
			result_tail++;
			p++;
			len--;
			is_pre_space = false;
		}
	}
	//移除尾部空格
	if (is_pre_space)
	{
		result_tail--;
	}
	*result_tail = '\0';
}

void main()
{	
	/*********************方法一************************************************/
	//这样会崩溃的,因为常量字符串不可以改变!!!!
	//char *s = "abc    d   \n  abc";
	/*********************************************************************/

	/***************************方法二******************************************/
    //char *s = (char *)malloc(sizeof(100));
	//gets(s);
	/***************但是这个不能输入 \n  ******************/

	/*****方法三,这个可以*****************************************/
	char s[] = "abc   d   \n  abc";
	RemoveExtraSpace(s,strlen(s));
	puts(s);
}

抱歉!评论已关闭.