目录

C 语言常用库函数-strsep

原则

  • 不要使用 strtok,需要类似功能用 strsep 代替。

strtok

函数原型

1
2
3
#include <string.h>

char *strtok(char *str, const char *delim);

用法分析

不要使用这个函数,除非你确切的了解它,并且知道你现在在作什么! strtok 用到了静态变量,从而导致了其不可重入的特性,对于不清楚的情况下使用是非常危 险的。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <string.h>

int main()
{
    char string[] = "Hello there, peasants!";
    char *found;

    printf("Original string: '%s'\n",string);

    found = strtok(string, " ");
    if( found == NULL)
    {
        printf("\t'%s'\n", string);
        puts("\tNo separators found");
        return(1);
    }
    while(found)
    {
        printf("\t'%s'\n", found);
        found = strtok(NULL, " ");
    }

    return(0);
}

输出为:

1
2
3
4
Original string: 'Hello there, peasants!'
    'Hello'
    'there,'
    'peasants!'

strsep

函数原型

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#include <string.h>

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

/*
函数说明: 使用字符串 delim 中的字符拆分字符串 *stringp,delim 可以由多个字符组成,
任意一个字符都将作为分隔符对待。

返回值: 当 *stringp 为 NULL 的时候,直接返回NULL;当找到 token 的时候,返回第
一个 token(以\0结束),*stringp 指向 delim后的一个字符。当没有找到的时候,返回
的token为整个字符串 *stringp,同时把 *stringp置 NULL(下一次查找的时候就
返回NULL了)
*/

用法分析

完成了和 strtok 类似的功能,但比 strtok 要安全的多。

举例说明:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char ptr[] = "abcdefghijklmnopqrstuvwxyz";
    char *p, *q, *str = "m";
    char *token;

    p = ptr;
    q = ptr;

    printf("%s\n", strsep(&p, str)); /* output "abcdefghijkl" */
    printf("%s\n", p);               /* output "nopqrstuvwxyz" */

    str = "s";

    printf("%s\n", strsep(&p,str));  /* output "nopqr" */
    printf("%s\n", p);               /* output "tuvwxyz" */

    while ((token = strsep(&q, str)) != NULL)
    {
        printf("token = %s, q = %s\n", token, q);
        // output "token = abcdefghijkl, q = (null)"
        // because q is "abcdefghijkl" before the loop
    }

    return 0;
}

实例参考

实例一

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <string.h>

void main()
{
    char str1[] = "hello world";
    char str2[] = "hello\tworld";
    char str3[] = "hello\nworld";
    char *p, *word1;

    p = str1;
    word1 = strsep(&p, "\t \n");
    printf("%s\n", word1);           /* output "hello" */

    p = str2;
    word1 = strsep(&p, "\t \n");
    printf("%s\n", word1);           /* output "hello" */

    p = str3;
    word1 = strsep(&p, "\t \n");
    printf("%s\n", word1);           /* output "hello" */

    return;
}