strsep函数用法

来源:互联网 发布:mac照片下一张 编辑:程序博客网 时间:2024/06/06 02:09

strsep(),作为strtok的升级版,是一个很有用的字符串处理函数, 但是也有很多不方便的地方, 使用时需特别小心, 好在注意的事项都在 man strsep 里面有。如下:

#include <string.h>

       char *strsep(char **stringp, const char *delim);

Be cautious when using this function.  If you do use it, note that:

       * This function modifies its first argument.

       * This function cannot be used on constant strings.

       * The identity of the delimiting character is lost.

实例:

#include <string>

#include <stdio.h>

int main(int arg, const char *argv[])

{

    char* string = strdup( "/home/yinlijun/project:/home/yinlijun:/home/someone");          /*字符串不能为常量,所以strdup*/
    char* p;

    while((p = strsep(&string, ":")) != NULL)        /*第一个参数设为二级指针, 字符串中所有的第二个参数(子串)最后会被替代成‘/0’*/
    {
        printf("%s/n", p);
    }

    return 0;

}

运行结果:

/home/yinlijun/project

/home/yinlijun

/home/someone

-----------------------------------------------OVER------------------------------------------


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/yinlijun2004/archive/2010/07/16/5740068.aspx