剑指Offer----扩展:空格问题(京东)

问题描述:


给定字符串(ASCII码0-255)数组,请在不开辟额外空间的情况下删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。
例如:" i am a little boy. ",变成"i am a little boy",语言不限,但不要用伪代码作答,函数输入输出请参考如下的函数原型:

C++函数原型:
void FormatString(char str[],int len){
}


方法一:


首先申明一点,方法一中只是解决了该问题,并没有按照题目中给定的要求来做,如:在此方法中,申请了额外的空间。

该方法是利用stringstream函数每次读取一个单词的特性,源代码如下:

源代码:


#include<iostream>
#include<string>
#include<sstream>

using namespace std;

void FormatString(char str[], int len)
{
	if (str == nullptr || len <= 0)
		return;

	string mystr(str);
	stringstream sst(mystr);

	int i = 0;
	string word;
	while (sst >> word)
	{
		int len = word.length();
		for (int j = 0; j < len; ++j)
			str[i++] = word[j];
		str[i++] = ' ';
	}
	str[i-1] = '\0';
}

int main()
{
	char str[] = "   I   am    a    little    boy.      ";
	cout << "Before format : " << str << endl;
	FormatString(str, sizeof(str) / sizeof(char));
	cout << "After format : " << str << endl;

	cout << __DATE__ << "  " << __TIME__ << endl;
	system("pause");
	return 0;
}

方法二:


其实这道题还挺有难度的,如果考虑的过多,必然会导致代码的冗余量非常大!
首先,应该找到第一个空格字符,然后考虑移位的为题,当且仅当字符后边有一个空格的时候才会移位,否则找到最后一个空格字符,在进行移位!


源代码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>

void FormatString(char str[], int len)
{
	if (str == NULL || len <= 0)
		return;
	int i = 0, j = 0;
	while (str[i] == ' ')//找到第一个空格
		++i;
	while (str[i] != '\0')
	{
		if (str[i] == ' '&& str[i + 1] == ' ' || str[i + 1] == '\0')
		{
			i++;
			continue;
		}

		str[j++] = str[i++];
	}
	str[j] = '\0';
}

int main(){
	char str[] = "     i    am a      little boy.    ";

	printf("Before format :%s\n", str);
	FormatString(str, sizeof(str));
	printf("After fromat  :%s\n", str);

	printf("%s  %s\n", __DATE__, __TIME__);
	system("pause");
	return 0;
}

运行结果:
Before format :     i    am a      little boy.
After fromat  :i am a little boy.
Aug 29 2016  15:56:29
请按任意键继续. . .



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值