在处理字符串的程序当中,经常会分析字符串,从一大长串的字符串截取我们需要的数据,这如果通过自己手写函数来分析,虽然可以,但当你知道sscanf的功能,那就自己写函数分析就显得多此一举。
这些函数的使用都很简单,总结一下,等下次使用一目了然。俗话说:好记性不如烂笔头,记录下来就是效率。
以下源代码是本人测试的源文件,附带讲解注释。
-
-
-
-
-
-
-
- #include
- #include
- #include
-
- static void sscanf_test(void);
-
- static void sscanf_test(void)
- {
- int ret;
- char *string;
- int digit;
- char buf1[255];
- char buf2[255];
- char buf3[255];
- char buf4[255];
-
-
- string = "china beijing 123";
- ret = sscanf(string, "%s %s %d", buf1, buf2, &digit);
- printf("1.string=%s\n", string);
- printf("1.ret=%d, buf1=%s, buf2=%s, digit=%d\n\n", ret, buf1, buf2, digit);
-
-
-
-
-
-
-
- string = "123456789";
- sscanf(string, "%5s", buf1);
- printf("2.string=%s\n", string);
- printf("2.buf1=%s\n\n", buf1);
-
-
-
-
-
-
- string = "123/456";
- sscanf(string, "%[^/]", buf1);
- printf("3.string=%s\n", string);
- printf("3.buf1=%s\n\n", buf1);
-
-
-
-
-
-
- string = "123abcABC";
- sscanf(string, "%[^A-Z]", buf1);
- printf("4.string=%s\n", string);
- printf("4.buf1=%s\n\n", buf1);
-
-
-
-
-
-
- string = "0123abcABC";
- sscanf(string, "%[0-9]%[a-z]%[A-Z]", buf1, buf2, buf3);
- printf("5.string=%s\n", string);
- printf("5.buf1=%s, buf2=%s, buf3=%s\n\n", buf1, buf2, buf3);
-
-
-
-
-
-
- string = "ios<>wp7";
- sscanf(string, "%*[^<]<%[^>]", buf1);
- printf("6.string=%s\n", string);
- printf("6.buf1=%s\n\n", buf1);
-
-
-
-
-
-
- string = "iosVSandroid";
- sscanf(string, "%[a-z]VS%[a-z]", buf1, buf2);
- printf("7.string=%s\n", string);
- printf("7.buf1=%s, buf2=%s\n\n", buf1, buf2);
-
-
-
-
-
-
- string = "android-iphone-wp7";
-
-
-
-
- sscanf(string, "%[^-]-%[^-]-%[^-]", buf1, buf2, buf3);
- printf("8.string=%s\n", string);
- printf("8.buf1=%s, buf2=%s, buf3=%s\n\n", buf1, buf2, buf3);
-
-
-
-
-
-
- string = "Email:beijing@sina.com.cn";
- sscanf(string, "%[^:]:%[^@]@%[^.].%s", buf1, buf2, buf3, buf4);
- printf("9.string=%s\n", string);
- printf("9.buf1=%s, buf2=%s, buf3=%s, buf4=%s\n\n", buf1, buf2, buf3, buf4);
-
-
-
-
- }
-
- int main(int argc, char **argv)
- {
- sscanf_test();
-
- return 0;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
阅读(1214) | 评论(0) | 转发(0) |