sscanf巧用格式字符串。

名称:

sscanf()  从一个字符串中,读入指定格式的数据。

函数定义:

 int sscanf( const char *buffer, const char *format [, argument ] ... );

参数:

buffer

Stored data.

format
Format-control string.
argument
Optional arguments.


Return Values
Each of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.

其中的format可以是一个或多个 {%[*] [width] [{h | l | I64 | L}]type | ' ' | '/t' | '/n' | 非%符号}
注:
  1、 * 亦可用于格式中, (即 %*d 和 %*s) 加了星号 (*) 表示跳过此数据不读入. (也就是不把此数据读入参数中)
  2、{a|b|c}表示a,b,c中选一,[d],表示可以有d也可以没有d。
  3、width表示读取宽度。
  4、{h | l | I64 | L}:参数的size,通常h表示单字节size,I表示2字节 size,L表示4字节size(double例外),l64表示8字节size。
  5、type :这就很多了,就是%s,%d之类。
  6、特别的:%*[width] [{h | l | I64 | L}]type 表示满足该条件的被过滤掉,不会向目标参数中写入值
  支持集合操作:
  %[a-z] 表示匹配a到z中任意字符,贪婪性(尽可能多的匹配)
  %[aB'] 匹配a、B、'中一员,贪婪性
  %[^a] 匹配非a的任意字符,贪婪性


例子:

1、常见用法。提取前n个字符

char buff[1024] = {0, };
sscanf("1234567890", "%3s", buff);

结果为:123

2、取到指定字符为止的字符串。在下例中,取遇到'@'为止的字符串

char buff[1024] = {0, };
sscanf("shaozg1101@126.com", "%[^@]", buff);

结果为:shaozg1101

3、取到指定字符集的字符串。在下例中,取仅包含小写字母的串

char buff[1024] = {0, };
sscanf("abcde12345ABCDE", "%[a-z]", buff);

结果为:abcde

4、给定一个字符串,提取中间的部分。在下例中,取google

char buff[1024] = {0, };
sscanf("http://www.google.com.hk", "%*[^.].%[^.]", buff);

结果为:google

5、提取表名。在下例中,提取table

char buff[1024] = {0, };
sscanf("user.table", "%*[^.].%s", buff);

结果为:table

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值