February 2009 Archives

哈,最近autoconf又有心得了

最近在阿里搜索技术中心搞了一次讲座,关于autoconf的,以前马马虎虎,好多的细节都没有注意,这次要给别人讲,那么我更得好好的“备备课”了,经过一番查阅资料,感觉效果还不错。


C语言去除空白字符

看了终南写的一文,觉得还是有些需要改进之处。

空白字符指空格、水平制表、垂直制表、换页、回车和换行符,他的方法如下:

#include <string.h>
#include <ctype.h>

char *trim(char *str)
{
        char *p = str;
        char *p1;
        if(p)
        {
                p1 = p + strlen(str) - 1;
                while(*p && isspace(*p)) p++;
                while(p1 > p && isspace(*p1)) *p1-- = '\0';
        }
        return p;
}

如这里面有2处“不科学”之处:

1,while(p1 > p && isspace(*p1)),如果右边空白比较多,那么每次都要比较p1和p的大小,不合理;

2,*p1 -- = '\0'每次while为真,那么*p1自减之后还要赋值一次,多此一举;

比较高效的方法如下:

char *trim(char *str)
{
    char *p = str;
    while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
        p ++;
    str = p;
    p = str + strlen(str) - 1;
    while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')
        -- p;
    *(p + 1) = 0;
    return str;
}

值得注意的是,此方法返回的是已经修改的字串,而且字串的长度小于等于原字串的长度。


Archives

Pages

Powered by Movable Type 7.0.4

April 2019

Sun Mon Tue Wed Thu Fri Sat
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30        
Creative Commons License
This blog is licensed under a Creative Commons License.

About this Archive

This page is an archive of entries from February 2009 listed from newest to oldest.

January 2009 is the previous archive.

March 2009 is the next archive.

Find recent content on the main index or look in the archives to find all content.