去掉字符串中的所有空格
2013-06-09 11:35
288 查看
要去掉字符串中所有的空格,思路很自然:碰到一个空格,将其删掉,然后后面的字符前移,但当空字符比较多的时候,总这么移动,难道不复杂么?还是想想另外的办法吧。
上面的方法时间复杂度比较高,下面,我们用空间来换时间:
上面这个思路不错,但是,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); } 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.
相关文章推荐
- 两列字段,合并成一个字符串,并且中间加一个符号,并去掉所有的空格
- js去掉字符串中所有空格
- 如何去掉C#字符串中的所有空格
- js去掉字符串中所有空格
- 如何用javascript去掉字符串里的所有空格
- 自己编写的去掉字符串中的所有空格函数trim_all
- 第十六周项目2-用指针玩字符串(任务六:去掉所有多余空格)
- 将字符串 “ hello word,你 好 世 界 ! ” 两端空格去掉并且将其中的其他所有空格替换成一个空格 输出结果为“hello word,你 好 世界”
- js去掉html标签和去掉字符串文本的所有的空格
- js去掉html标签和去掉字符串文本的所有的空格
- sed去掉字符串所有空格
- 将字符串中的所有空格去掉,要求时间复杂度O(N)
- 去掉字符串左边的所有空格
- C#如何去掉字符串中所有空格
- 去掉字符串中的所有空格
- JS去掉字符串中所有空格
- js 去掉字符串前后所有空格
- JS去掉字符串中所有空格
- javascript去掉字符串里的所有空格
- 去掉字符串中所有空格