C语言 strtok

C语言 strtok

#include <string.h>
char *strtok(char *str, const char *delim);

功能:来将字符串分割成一个个片段。当strtok()在参数s的字符串中发现参数delim中包含的分割字符时, 则会将该字符改为\0 字符,当连续出现多个时只替换第一个为\0。
参数:

  • str:指向欲分割的字符串
  • delim:为分割字符串中包含的所有字符

返回值:

  • 成功:分割后字符串首地址
  • 失败:NULL

在第一次调用时:strtok()必需给予参数s字符串
往后的调用则将参数s设置成NULL,每次调用成功则返回指向被分割出片段的指针

案例

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    // 字符串截取 strtok 会破坏源字符串,会用\0替换分隔的标志位
    char ch[] = "www.xsk.cn";
    // 1、www\0xsk.cn
    // 2、www\0xsk\0cn
    // 3、www\0xsk\0cn\0


    // 1、截取“.”之前内容
    char* p = strtok(ch, ".");
    printf("%s\n", p);

    // 2、打印另外一个标示为
    p = strtok(NULL, ".");
    printf("%s\n", p);

    // 3、打印另外一个标示为
    p = strtok(NULL, ".");
    printf("%s\n", p);

    // 查看内存地址
    // printf("%p\n", p);
    // printf("%p\n", ch);
    return 0;
}
strtok 使用案例
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    // 截取qq号、保留源邮箱
    char ch[] = "[email protected]";
    char str[100] = { 0 };
    
    // 字符串备份
    strcpy(str, ch);

    // 截取qq
    char* p = strtok(str, "@");
    printf("%s\n", p);

    // 截取代理邮箱
    p = strtok(NULL, ".");
    printf("%s\n", p);

    return 0;
}
strtok 使用案例:2
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main(void)
{
    
    char ch[] = "woqunimalege\nbideni\nkannimabi\nageilaozigun\n";
    char* p = strtok(ch, "\n");
    while (p)
    {
        printf("%s\n", p);
        p = strtok(NULL, "\n");
    }
    return 0;
}
strtok 使用案例:3

猜你喜欢

转载自www.cnblogs.com/xiangsikai/p/12378574.html