C语言字符串拆分的两种方式strtok和正则表达式

一、利用strtok()函数进行分割
函数头文件#include<string.h>
函数原型:char *strtok(char s[], const char *delim); s[]是原字符串,delim为分隔符
函数返回被分解的第一个子字符串,若无可检索的字符串,则返回空指针
特性:
1)strtok拆分字符串是直接在原串上操作,所以要求参1必须可读可写
2)第一次拆分,参1传待拆分的原串。第1+次拆分时,参1传NULL

#include<string.h>
#include <stdio.h>
int main()
{
    char str[] = "abc.def.12";
    char *index = NULL;
    char id[128] = {0};
    index = strtok(str, ".");
    while (index != NULL)
    {
        strncpy(id, index, sizeof(id));
        index = strtok(NULL, ".");
    }
    printf("%s\n", id);
}

编译输出:

test# gcc 1.c -o out
test# ./out
12

二、利用正则表达式实现
函数原型:int sscanf (char *str, char * format [, argument, …]);
与scanf()区别,scanf的输入是在键盘输入的,而sscanf()是在用户定义的缓冲区获取的固定格式的数据。
返回值:读取成功的参数个数,失败是-1

#include<stdio.h>
int main()
{
    char str[] = "123@qq.com";
    int b;
    char c[10];
    char d[10];
    int n=sscanf(str, "%d@%[a-z].%[a-z]", &b, c, d);
    printf("用户名%d\n", b);
    printf("邮箱类型%s\n", c);
    printf("第三部分%s\n", d);
    printf("返回值%d\n", n); //读取成功的参数个数
}

编译输出:

test# gcc 2.c -o out
test# ./out
用户名123
邮箱类型qq
第三部分com
返回值3

转自:https://blog.csdn.net/qq_45313714/article/details/116044440

参考:字符分割函数strtok

posted @ 2022-12-16 10:47  船长博客  阅读(544)  评论(0编辑  收藏  举报
永远相信美好的事情即将发生!