C语言写的trim()函数

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 函数

 1 #include <string.h>
 2 #include <ctype.h>
 3 
 4 char *trim(char *str)
 5 {
 6         char *p = str;
 7         char *p1;
 8         if(p)
 9         {
10                 p1 = p + strlen(str) - 1;
11                 while(*p && isspace(*p)) p++;
12                 while(p1 > p && isspace(*p1)) *p1-- = '/0';
13         }
14         return p;
15 }

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

 转自:http://blog.csdn.net/fengrx/article/details/4163148

原文地址:https://www.cnblogs.com/liushui-sky/p/5584763.html