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 @   船长博客  阅读(776)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-12-16 使用docker镜像搭建Python3 jupyter notebook环境
2020-12-16 用Python合并多个Excel文件
2020-12-16 vscode保存文件时自动删除行尾空格
永远相信美好的事情即将发生!
点击右上角即可分享
微信分享提示