利用忽略和匹配完成输出(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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值