sscanf函数用法,C语言中sscanf函数6种用法详解
sscanf()函数实现:
不管接触过任何编程语言也好,学过正则表达式的都对sscanf()的使用并不陌生了。如何通过sscanf将已知的字符串通过格式化匹配出有效的信息?下面我把要实现对象的方法和作用意义给列出来,如下所示:
格式 | 作用 |
---|---|
%*s或%*d | 跳过数据 |
%[width]s | 读指定宽度的数据 |
%[a-z] | 匹配a到z中任意字符(尽可能多的匹配) |
%[aBc] | 匹配a、B、c中一员,贪婪性 |
%[^a] | 匹配非a的任意字符,贪婪性 |
%[^a-z] | 表示读取除a-z以外的所有字符 |
以上有六种方法,每种方法都来实现以下:
函数原型为:int sscanf(const char *const_Buffer, const char*const _Format, ...)
作用:从一个字符串中读进与指定格式相符的数据的函数
第1种方法:
利用%*s或%*d的格式实现跳过数据:
代码如下所示:
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>voidtest(){char* str1 ="666helloworld";char temp1[128]={0};sscanf(str1,"%*d%s", temp1);printf("%s\n", temp1);// 得到的是helloworldprintf("---------------\n");char* str2 ="helloworld666";char temp2[128]={0};sscanf(str2,"%*[a-z]%s", temp2);printf("%s\n", temp2);// 得到的是666}intmain(){test();system("pause");return0;}
结果图为:
第2种方法:
通过%[width]s格式进行读指定宽度的数据:
代码如下所示:
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>voidtest(){char* str1 ="666helloworld";char temp1[128]={0};sscanf(str1,"%8s", temp1);printf("%s\n", temp1);// 得到的是666hello}intmain(){test();system("pause");return0;}
第3种方法:
通过%[a-z]格式进行匹配a到z中任意字符(尽可能多的匹配):
代码如下所示:
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>voidtest(){char* str1 ="666helloworld";char temp1[128]={0};sscanf(str1,"%*d%[a-z]", temp1);printf("%s\n", temp1);// 得到的是helloworld}intmain(){test();system("pause");return0;}
第4种方法:
通过%[aBc]格式进行匹配a、B、c中的一员,贪婪性正则表达式
代码如下所示:
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>voidtest(){char* str1 ="abccabchelloworld";char temp1[128]={0};sscanf(str1,"%[abc]", temp1);// 如果刚开始就遇到匹配失败,后续则不再匹配printf("%s\n", temp1);// 得到的是abccabc}intmain(){test();system("pause");return0;}
第5种方法:
通过方法: %[^a]格式进行匹配非a的任意字符,也属于贪婪性正则表表达式
代码如下所示:
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>voidtest(){char* str1 ="abccabchelloworld";char temp1[128]={0};sscanf(str1,"%[^c]", temp1);// 如果匹配到字符,则字符后面的不在进行匹配printf("%s\n", temp1);// 得到的是ab}intmain(){test();system("pause");return0;}
第6种方法:
通过%[^a-z]格式,进行匹配读取除a-z以外的所有字符
代码如下所示:
#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<string.h>#include<stdlib.h>voidtest(){char* str1 ="hello52wo3rld";char temp1[128]={0};sscanf(str1,"%[^0-9]", temp1);// 如果匹配到字符,则字符后面的不在进行匹配printf("%s\n", temp1);// 得到的是hello}intmain(){test();system("pause");return0;}
本文地址:百科问答频道 https://www.neebe.cn/wenda/936152.html,易企推百科一个免费的知识分享平台,本站部分文章来网络分享,本着互联网分享的精神,如有涉及到您的权益,请联系我们删除,谢谢!