- 将已知的字符串通过格式化匹配出有效信息
- 案例
- 字符串 char * str = “abcde#zhangtao@12345” 中间的zhangtao匹配出来
- 匹配char * ip = “127.0.0.1”将中间数字匹配到 num1 ~ num4中
%*s或%*d 跳过数据
void test01()
{
char * str = "12345abcde";
char buf[1024] = { 0 };
sscanf(str, "%*d%s", buf);
printf("%s\n", buf);
}
void test02()
{
char * str = "abcde12345"; //在中间加空格或者\t都可以实现效果
char buf[1024] = { 0 };
//sscanf(str, "%*s%s", buf);
sscanf(str, "%*[a-z]%s", buf);
printf("%s\n", buf);
}
%[width]s 读指定宽度的数据
void test03()
{
char * str = "12345abcde";
char buf[1024] = { 0 };
sscanf(str, "%6s", buf);
printf("%s\n", buf);
}
%[a-z] 匹配a到z中任意字符(尽可能多的匹配)
void test04()
{
char * str = "12345abcde";
char buf[1024] = { 0 };
sscanf(str, "%*d%[a-c]", buf);
printf("%s\n", buf);
}
%[aBc] 匹配a、B、c中一员,贪婪性
void test05()
{
char * str = "aabcde12345";
char buf[1024] = { 0 };
sscanf(str, "%[aBc]", buf); //在匹配过程中,只要有一个匹配失败,后续就不在进行匹配
printf("%s\n", buf);
}
%[^a-z] 表示读取除a-z以外的所有字符
void test07()
{
char * str = "abcde12345";
char buf[1024] = { 0 };
sscanf(str, "%[^0-9]", buf);
printf("%s\n", buf);
}
案例1
void test08()
{
char * ip = "127.0.0.1";
int num1 = 0;
int num2 = 0;
int num3 = 0;
int num4 = 0;
sscanf(ip, "%d.%d.%d.%d", &num1, &num2, &num3, &num4);
printf("%d\n", num1);
printf("%d\n", num2);
printf("%d\n", num3);
printf("%d\n", num4);
}
void test09()
{
char * str = "abcde#zhangtao@12345";
char buf[1024] = { 0 };
sscanf(str, " %*[^#]#%[^@] ", buf);
printf("%s\n", buf);
}
已给定字符串为: helloworld@itcast.cn,请编码实现helloworld输出和itcast.cn输出。
void test10()
{
char * str = "helloworld@itcast.cn";
char buf1[1024] = { 0 };
char buf2[1024] = { 0 };
sscanf(str, "%[a-z]%*[@]%s", buf1, buf2);
printf("%s\n", buf1);
printf("%s\n", buf2);
}
int main() {
char *str = "helloworld@itcast.cn";
char buf1[1024] = { 0 };
char buf2[1024] = { 0 };
//sscanf(str, "%10s", buf1);
//sscanf(str, "%[a-z]", buf1);
sscanf(str, "%[^@]", buf1);
sscanf(str, "%*[^@]@%s", buf2);
printf("buf1:%s\n", buf1);
printf("buf2:%s\n", buf2);
system("pause");
return 0;
}