例子: 原 " asd asda123 as ",返回字符串为“asd asda123 as”;
解题思路:
我们用另外一个字符串p去存储掉无效空格后的字符串,由原字符串开始往后遍历,首先去除开头的空字符,之后令一变量cnt等于空格出现的次数,一旦cnt>0并且不属于字符串尾端,就在p后面加上空格。代码如下:
#include<iostream>
#include<stdio.h>
using namespace std;
char* formatString(char *sourceString) ;
void main()
{
char a[]=" asd asda123 as ";
char b[]=" ";
char* c=formatString(a) ;
char* d=formatString(b) ;
}
char* formatString(char *sourceString)
{
if(sourceString==NULL||sourceString=='\0') return NULL;
char *temp=sourceString;
while(*temp==' ')
temp++;
int n=strlen(sourceString);
char *p=new char[n+1];
p[n]='\0';
int length=0;//去掉空格之后新的字符串的长度
while(*temp!='\0')
{
int cnt=0;
while(*temp==' ')
{
temp++;
cnt++;
}
if(cnt>0&&*temp!='\0')
{
*p=' ';
p++;
length++;
}
if(*temp!=' '&&*temp!='\0')
{
*p=*temp;
p++;
temp++;
length++;
}
}
p=p-length;
p[length]='\0';
return p;
}