zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Golang判断文件/文件夹是否存在
    Golang将一个文件中的内容写入到另一个文件里
    Golang打开已存在的文件并覆盖其内容
    Golang打开文件并写入
    【正则】day01
    【正则】day02
    【day09】PHP
    【day08】PHP
    转换函数
    变量作用域
  • 原文地址:https://www.cnblogs.com/liushui-sky/p/5584763.html
Copyright © 2011-2022 走看看