一、scanf函数
scanf() - 以屏幕(stdin)为输入源,提取输入指定格式的数据,返回提取的数据个数。
函数原型:int scanf( const char *format [,argument]... );
二、sscanf函数
sscanf() - 从一个字符串中读进与指定格式相符的数据,非常适合字符获取,例如提取IP,网址域名,邮箱用户名等等。
函数原型:Int sscanf( string str, string format , mixed var1, mixed var2 ... );
说明:
其中的format可以是一个或多个 {%[*] [width] [{h | l | I64 | L}]type | ' ' | '/t' | '/n' | 非%符号}
注:
- * 亦可用于格式中, (即 %*d 和 %*s) 加了星号 (*) 表示跳过此数据不读入. (也就是不把此数据读入参数中)
- {a|b|c}表示a,b,c中选一,[d],表示可以有d也可以没有d。
- width表示读取宽度。
- {h | l | I64 | L}:参数的size,通常h表示单字节size,I表示2字节 size,L表示4字节size(double例外),l64表示8字节size。
- type :这就很多了,就是%s,%d之类。
- 特别的:%*[width] [{h | l | I64 | L}]type 表示满足该条件的被过滤掉,不会向目标参数中写入值
支持集合操作:
- %[a-z] 表示匹配a到z中任意字符,贪婪性(尽可能多的匹配)
- %[aB'] 匹配a、B、'中一员,贪婪性
- %[^a] 匹配非a的任意字符,贪婪性
三、用法
3.1 最简单的用法
string = "china beijing 123";
ret = sscanf(string, "%s %s %d", buf1, buf2, &digit);
3.2 取指定长度的字符串
string = "123456789";
sscanf(string, "%5s", buf1);
3.3 取到指定字符为止的字符串
string = "123/456";
sscanf(string, "%[^/]", buf1);
3.4 取到指定字符集为止的字符串
string = "123abcABC";
sscanf(string, "%[^A-Z]", buf1);
3.5 取仅包含指定字符集的字符串
string = "0123abcABC";
sscanf(string, "%[0-9]%[a-z]%[A-Z]", buf1, buf2, buf3);
3.6 获取指定字符中间的字符串
string = "ios<android>wp7";
sscanf(string, "%*[^<]<%[^>]", buf1);
3.7 指定要跳过的字符串
string = "iosVSandroid";
sscanf(string, "%[a-z]VS%[a-z]", buf1, buf2);
3.8 分割以某字符隔开的字符串
string = "android-iphone-wp7";
sscanf(string, "%[^-]-%[^-]-%[^-]", buf1, buf2, buf3);
3.9 提取邮箱地址
string = "Email:beijing@sina.com.cn";
sscanf(string, "%[^:]:%[^@]@%[^.].%s", buf1, buf2, buf3, buf4);
3.10 过滤掉不想截取或不需要的字符串--补充,
string = "android iphone wp7";
sscanf(string, "%s %*s %s", buf1, buf2);
参考:
1:Linux C语言中sscanf 的详细用法