删除字符串开始和末尾的空白,若中间有多个空格转化为一个。
思路:先删除开头和结尾的空格,再将中间连续的空格转化为一个
#include <iostream>
#include<string.h>
using namespace std;
char *delSpace(char * a)
{
if(a==NULL)
return NULL;
char *ps=a;
char *pe=a+strlen(a);
//删除开头空格
while(*ps=='-')
ps++;
//删除尾部空格
pe--;
while(*pe=='-')
pe--;
*pe='\0';
pe=a;
//cout<<"ps"<<ps<<endl;
while(*ps!='\0')
{
while(*ps=='-')
{
ps++;
}
//查看是否为连续的空格,若是,变为一个,pe!=a为了防止开头存在连续空格的情况
if(*(ps-2)=='-'&&*(ps-1)=='-'&&pe!=a)
{
*pe++='-';
}
//保留非连续的空格
else if(*(ps-2)!='-'&&*(ps-1)=='-')
{
*pe++='-';
}
*pe=*ps;
pe++;
ps++;
}
*pe='\0';
return a;
}
int main()
{
char s1[100]="----How-are-you?";
char s2[100]="hello----world!";
char s3[100]="welcome-here!----";
char s4[100]="-----thank-------you!----";
cout<<s1<<endl;
cout<<delSpace(s1)<<endl;
cout<<s2<<endl;
cout<<delSpace(s2)<<endl;
cout<<s3<<endl;
cout<<delSpace(s3)<<endl;
cout<<s4<<endl;
cout<<delSpace(s4)<<endl;
return 0;
}
输出结果:
----How-are-you?
How-are-you
hello----world!
hello-world
welcome-here!----
welcome-here
-----thank-------you!----
thank-you