zoukankan      html  css  js  c++  java
  • 60. 去字符串中的空格,去左空格,去右空格,去全部空格。

    现在情况是,在现有的待处理字符串中,中间,左边,右边可能都会有空格。

      1 //去字符串中的空格,只去左空格,只去右空格,去全部空格。
      2 #include <stdio.h>
      3 
      4 /*只去除右边空格*/
      5 
      6 void trimStrRightSpace(char *str)
      7 {
      8 #if 0 //思路:先移动到末尾,再往左遍历,直到遇到非空格为止。再回退一次,置个0
      9     while(*str)
     10         str++;
     11     while(*(--str) == ' ');
     12     *(++str) = '';
     13 #endif
     14 
     15 #if 1//思路:先移动到末尾,再往左遍历,碰见的空格全部置0,直到碰见非空格为止。
     16     while(*str)
     17         str++;
     18     while(*(--str) == ' ')
     19         *str = '';
     20 #endif
     21 }
     22 
     23 
     24 
     25 
     26 
     27 /*只去除左边空格,去空格的同时需要用后边的有效字符把空格覆盖*/
     28 //基础版
     29 void trimStrLeftSpace1(char *str)
     30 {
     31     //一个指针先移动到非空格, 然后依次把非空格字符拷贝移动到左边,包括
     32     char* p = str;
     33     while(*p == ' ')
     34         p++;
     35     while(*str++ = *p++);
     36 }
     37 //如果本来就没空格,上面的代码那就是瞎拷贝一次浪费时间。
     38 
     39 //优化版  如果左边没空格则不不进行无意义的拷贝操作,
     40 void trimStrLeftSpace2(char *str)
     41 {
     42     if(*str != ' ')
     43         return;
     44 
     45     char* p = str;
     46     while(*p == ' ')
     47         p++;
     48     while(*str++ = *p++);
     49 }
     50 
     51 
     52 
     53 
     54 
     55 
     56 /*去除全部空格*/ //1和2逻辑一样,只是变形,2更好
     57 //等于空格时,s不动,p往前走
     58 //不等于空格时,拷贝,s往前走,p往前走
     59 void trimStrAllSpace1(char* str)
     60 {
     61     char* p = str;
     62     while(*p)
     63     {
     64         if(*p == ' ')
     65         {
     66             p++;
     67 
     68         }
     69         else
     70         {
     71             *str = *p;
     72             p++;
     73             str++;
     74         }
     75     }
     76     *str = '';
     77 }
     78 //p碰到非空格,进行拷贝
     79 //p碰见空格,越过
     80 void trimStrAllSpace2(char* str)
     81 {
     82     char* p = str;
     83     while(*p)
     84     {
     85         if(*p != ' ')
     86             *str++ = *p;
     87         p++;
     88     }
     89     *str ='';
     90 }
     91 
     92 
     93 
     94 int main(void)
     95 {
     96     char str[] = "   ab  c de   ";
     97    // trimStrRightSpace(str);
     98    // trimStrLeftSpace2(str);
     99     trimStrAllSpace1(str);
    100     printf("|%s|
    ",str);
    101     return 0;
    102 }
  • 相关阅读:
    使用VMWare实现主机一拖二(笔记本分身术)
    Implementing RelativeSource binding in Silverlight
    CLRProfiler V4 Released
    Host WCF on IIS 7.5
    增加智能感知的RichTextBox扩展控件(WPF)
    Troubleshooting Visual Studio 2010 and QT 4.7 Integration
    windows命令行下如何查看磁盘空间大小
    模拟谷歌今日使用的css动画
    粗聊Mysql——你会建库建表么?
    彩票项目难点分析
  • 原文地址:https://www.cnblogs.com/ZhuLuoJiGongYuan/p/9555946.html
Copyright © 2011-2022 走看看