C语言写的trim()函数

来源:互联网 发布:mac 身份不明 编辑:程序博客网 时间:2024/05/01 18:59


C语言的标准库中缺少对字符串进行操作的trim()函数,使用起来有些不便,可以使用利用 strlen 和 isspace 函数以及指针来自己写一个。

1、strlen 函数

原型:extern int strlen(char *s);
        
用法:#include <string.h>

功能:计算字符串s的长度

说明:返回s的长度,不包括结束符NULL。

2、isspace 函数

原型:extern int isspace(int c);

用法:#include <ctype.h>

功能:判断字符c是否为空白符

说明:当c为空白符时,返回非零值,否则返回零。
   空白符指空格、水平制表、垂直制表、换页、回车和换行符。

3、trim 函数

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

4、应用举例

int main()
{
    int i = 0;
    char strs[][128] = {
        NULL,
        "",
        " ",
        "hello world",
        " hello",
        "hello world ",
        " hello world ",
        "\t\n\thello world ",
        "END"
    };

    do
    {
        printf("trim(\"%s\")=%s.\n", strs[i], trim(strs[i]));
    }while(strcmp(strs[i++], "END"));

    return 0;
}


原创粉丝点击