ssanf(source,"字符匹配",target)
sscanf,匹配从第一个字符开始
%*d%s 非数字,字符。
情况:
1、乱码,数据类型不是%s;
2、空白,没有间隔符(空格、\t、\n等)
%[abc] [abc]
%[^abc] [非abc]
%[a-z] a到z
%[^a-z] 非[a到z]
01 %*d%s
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void test1() {
char* str = "12345abcde";
char buf[1024] = { 0 };
sscanf(str, "%*d%s", buf);
printf("%s", buf);
}
void main() {
test1();
system("pause");
}
02 空格 \n \t
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void test2() {
char* str1 = "abcde12345";
char* str2 = "abcde 12345";
char* str3 = "abcde\t12345";
char* str4 = "abcde\n12345";
int buf1[1024] = { 0 };
char buf2[1024] = { 0 };
char buf3[1024] = { 0 };
char buf4[1024] = { 0 };
char buf5[1024] = { 0 };
sscanf(str1, "%*s%d", buf1);
sscanf(str1, "%*s%s", buf2);
sscanf(str2, "%*s%s", buf3);
sscanf(str3, "%*s%s", buf4);
sscanf(str4, "%*s%s", buf5);
printf("%d\n", buf1);
printf("%s\n", buf2);
printf("%s\n", buf3);
printf("%s\n", buf4);
printf("%s\n", buf5);
}
void main() {
test2();
system("pause");
}
03 [ab]、[ ^ab]、[a-z]、[ ^a-z]
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void test3() {
char* str = "abcde12345";
char buf1[1024] = { 0 };
char buf2[1024] = { 0 };
char buf3[1024] = { 0 };
char buf4[1024] = { 0 };
sscanf(str, "%[a-z]s", buf1);
sscanf(str, "%[^a-z]s", buf2);
sscanf(str, "%[ab]s", buf3);
sscanf(str, "%[^ab]s", buf4);
printf("%s\n", buf1);
printf("%s\n", buf2);
printf("%s\n", buf3);
printf("%s\n", buf4);
}
void main() {
test3();
system("pause");
}