删除字符串中的连续空格(只保留一个),O(n)时间复杂度,O(1)空间复杂度

来源:互联网 发布:js null与undefined 编辑:程序博客网 时间:2024/04/27 23:49
[cpp] view plaincopy
  1. //trim a string by make  more than one blank to one blank  
  2. char* trim(char* a)  
  3. {  
  4.     int i=-1,j=0;  
  5.     for (;a[j]!='\0';j++)  
  6.     {  
  7.         if (a[j]==a[j+1] && a[j+1]==' ')  
  8.         {  
  9.             //skip more than one blank  
  10.             while (a[j]==' ')  
  11.             {  
  12.                 ++j;  
  13.             }  
  14.             --j;// go back to the last blank  
  15.         }  
  16.         a[++i]=a[j];  
  17.     }  
  18.     a[++i]='\0';  
  19.     return a;  
  20. }  
  21. int main( void )   
  22. {  
  23.    
  24.     char a[100]="a b  c  d  e                  f";  
  25.     printf(a);  
  26.     printf(trim(a));  
  27.     return 0;  
  28. }  
原创粉丝点击