要去掉字符串中所有的空格,思路很自然:碰到一个空格,将其删掉,然后后面的字符前移,但当空字符比较多的时候,总这么移动,难道不复杂么?还是想想另外的办法吧。
上面的方法时间复杂度比较高,下面,我们用空间来换时间:
#include <iostream>
using namespace std;
void deleteAllSpace(char str[])
{
int len = strlen(str);
char *p = new char[len + 1];
int i, j = 0;
for(i = 0; i < len; i++)
{
if(' ' != str[i])
{
p[j++] = str[i];
}
}
p[j] = '\0';
strcpy(str, p);
}
int main()
{
char str1[] = "abc";
char str2[] = " abc";
char str3[] = "abc ";
char str4[] = " a b c ";
char str5[] = " a b c ";
char str6[] = " a bcd e ";
deleteAllSpace(str1);
deleteAllSpace(str2);
deleteAllSpace(str3);
deleteAllSpace(str4);
deleteAllSpace(str5);
deleteAllSpace(str6);
printf("%s\n", str1);
printf("%s\n", str2);
printf("%s\n", str3);
printf("%s\n", str4);
printf("%s\n", str5);
printf("%s\n", str6);
return 0;
}
上面这个思路不错,但是,main中的程序太丑陋了,改为如下:
#include <iostream>
using namespace std;
void deleteAllSpace(char str[])
{
int len = strlen(str);
char *p = new char[len + 1];
int i, j = 0;
for(i = 0; i < len; i++)
{
if(' ' != str[i])
{
p[j++] = str[i];
}
}
p[j] = '\0';
strcpy(str, p);
delete []p;
}
int main()
{
char str[6][20] =
{
"abc",
" abc",
"abc ",
" a b c ",
" a b c ",
" a bcd e "
};
int i;
for(i = 0; i < 6; i++)
{
deleteAllSpace(str[i]);
printf("%s\n", str[i]);
}
return 0;
}
事实上,上述程序的空间复杂度较高,那有没有更好的办法呢?有,如下:
#include <iostream>
using namespace std;
void deleteAllSpace(char str[])
{
char *p = str;
int k = 0;
while('\0' != *p)
{
if(' ' != *p)
{
str[k++] = *p++;
}
else
{
p++;
}
}
str[k] = '\0';
}
int main()
{
char str[6][20] =
{
"abc",
" abc",
"abc ",
" a b c ",
" a b c ",
" a bcd e "
};
int i;
for(i = 0; i < 6; i++)
{
deleteAllSpace(str[i]);
printf("%s\n", str[i]);
}
return 0;
}
OK.