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;
}

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


Monthly Archives

Pages

Powered by Movable Type 7.7.2

About this Entry

This page contains a single entry by Cnangel published on February 9, 2009 1:59 PM.

如何使用libxml2库? was the previous entry in this blog.

哈,最近autoconf又有心得了 is the next entry in this blog.

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