利用忽略和匹配完成输出(Sscanf)
一、Sscanf
1.%星号s 或者 %星号d:忽略字符串或者是数字
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
// 1、%*s或%*d
void test1()
{
char *str = "1234abcd";
char buf[1024] = {0};
sscanf(str, "%*d%s", buf);
printf("%s\n", buf);
}
void test2()
{
char *str = "abcd1234";
char buf[1024] = {0};
// sscanf(str,"%*s%s",buf);
// 此做法会忽略掉所有字符,达不到预期效果
// 另外忽略处理过程遇到空格或者\t会结束忽略
sscanf(str, "%*[a-z]%s", buf);
//注,即使用这个方法也没法保证1234开头的串达到效果,必须以字母开头才行
printf("%s\n", buf);
}
int main()
{
test1();
test2();
system("pause");
return 0;
}
2.%widths:保留定长
void test3()
{
char *str = "1234abcd";
char buf[1024] = {0};
sscanf(str, "%3s", buf); // 指定宽度
printf("%s\n", buf);
}
3.%[a-z]:保留a-z,但需要注意,若遇到匹配失败那么不再继续匹配
void test4()
{
char *str = "1234abcdaaa";
char buf[1024] = {0};
sscanf(str, "%*d%[a-c]", buf); //忽略数字的同时,保留a-c且不需要加%s
printf("%s\n", buf);//输出是abc,后续a不保留
}
4.%*[abD]:保留所含字符,若遇到匹配失败那么不再继续匹配
void test5()
{
char *str = "1234abDd";
char buf[1024] = {0};
sscanf(str, "%*d%[aD]", buf);
printf("%s\n", buf);
}
5.%[^]: 保留非某字符后,若遇到匹配失败那么不再继续匹配
void test6()
{
char *str = "1234abDd";
char buf[1024] = {0};
sscanf(str, "%*d%[^D]", buf);
printf("%s\n", buf);
}
二、给定字符串为:helloworld@itcast.cn,编码实现helloworl输出和itcast.cn输出
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
void test()
{
char *str = "helloworld@itcast.cn";
char str1[1024] = {0};
char str2[1024] = {0};
sscanf(str, "%[a-z]%*[@]%s", str1, str2);
printf("%s\n%s\n", str1, str2);
}
int main()
{
test();
system("pause");
return 0;
}