笔试题:字符串去除空格

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

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

答案:

#include <iostream>  
#include<assert.h>

void FormatString(char str[],int len)
{
	assert(str !=NULL || len <0 || str[len-1]!='\0');
	int i=0 , j=0;//, k =0;
	while( str[i] == ' ')i++; //find i;
	while( str[i] !='\0')//不要随意的使用while(str[i++])
	{
		 if (str[i] == ' ' && str[i+1] == ' ' || str[i+1] == '\0')//完善不容易
		{
			 i++;
			continue;
		 }
		str[j++] = str[i++];
	}
	str[j]='\0';
}

int main(){
 char a[]=" i    am a      little boy.    ";
 unsigned int len=strlen(a);
 printf("%s\n",a);
 FormatString(a,len);
 printf("%s\n",a);
 system("pause");
 return 0;
}

本文转自:http://www.nowcoder.com/questionTerminal/f05b77d89427428783c80e83e44a0f46

猜你喜欢

转载自blog.csdn.net/ding977921830/article/details/52440128