您的位置:首页 > 其它

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

2012-05-27 16:58 232 查看
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>

int Remove(char str[])
{
	if (NULL == str)
	{
		return 0;
	}
	//删除空格计数
	int removeCnt = 0;
	//扫描头
	int i = 0;
	//当前字符为'\n',new_line为真,初始为真,可去除开头的空格
	bool newline = true;
	while (str[i])
	{
		str[i - removeCnt] = str[i];
		//当前为空格
		if (' ' == str[i])
		{
			//新行后的空格,应该删除
			if (newline)
			{
				++removeCnt;
			}
			//空格后的空格,应该删除
			else if (' ' == str[i + 1])
			{
				++removeCnt;
			}
			//换行前的空格,应该删除
			else if ('\n' == str[i + 1])
			{
				++removeCnt;
			}
			//结尾的空格,应该删除
			else if (0 == str[i + 1])
			{
				++removeCnt;
			}
		}
		else if ('\n' == str[i])
		{
			newline = true;
		}
		else
		{
			newline = false;
		}
		++i;
	}
	str[i - removeCnt] = 0;
	return removeCnt;
}

void main()
{
	char s[] = "abc   \n    b    d    "; 
	printf("%d\n",Remove(s));
	puts(s);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: