问题:去除掉字符串中多余的空格,字符串的句首和句尾没有空格,中间的字符串单词只能保留一个空格。
解决方案:
直接上小代码,时间复杂度O(n)。
#include <iostream>
using namespace std;
void deblank(char string [] )
{
char *p = string;
//去掉首部空格
while(*p ==' ') {
p++;
}
//去掉中间多余空格
int j=0;
while(*p !=' ')
{
string[j++]=*p++;
while(string[j-1]==' '&&*p==' ')
{
p++;
}
}
//去掉最后一个可能的空格
if(string[j-1]==' ')
string[j-1]=' ';
else
string[j]=' ';
}
int main()
{
char s[] =" bnnn ad ssss sww df ";
deblank(s);
cout<<s;
return 0;
}