函数 —— strchr() 例如:字符串中的 192.168.1.2|00:11:22:33:44:55 取出字符串中的ip与mac值

char *strchr(const char *str, int c)

/*功能:
 * C 库函数 char *strchr(const char *str, int c) 在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。*/
/*参数:
 * str -- 要被检索的 C 字符串。
 * c -- 在 str 中要搜索的字符。*/
/*返回值:

 * 该函数返回在字符串 str 中第一次出现字符 c 的位置,如果未找到该字符则返回 NULL*/

int main()
{
        const char str[] = "http://www.runoob.com";
        const char ch = '.';
        char *ret;
        ret = strchr(str,ch);
        printf("|%c| 之后的字符串是 - |%s|\n",ch,ret); //|.| 之后的字符串是 - |.runoob.com|
        return 0;
}


解决问题:

    字符串中的 192.168.1.2|00:11:22:33:44:55 取出字符串中的ip与mac值

        当字符串中没有‘|’或者字符串为空时候,ip与mac的值 赋值为 ‘-’。

#include<stdio.h>
#include<string.h>
int ExtractIpMac(const char* buf,char* ip,char* mac)
{
        char *p = NULL;
        char *q = NULL;
        int len = strlen(buf);
        if(len <= 0)
                goto IPMACErr;

        q = strchr(buf,'|');
        if(q == NULL)
                goto IPMACErr;

        printf("q-buf=%d\n",q-buf);//11
        printf("len-(q-buf+1)=%d\n",len-(q-buf+1));//17
        strncpy(ip,buf,q-buf);
        strncpy(mac,q+1,len-(q-buf+1));
        return 0;

IPMACErr:
        printf("bb\n");
        strncpy(mac,"-",1);
        strncpy(ip,"-",1);
}
int main()
{
//      char buf[] = "";
        char buf[] = "192.168.1.2|00:11:22:33:44:55";
        char ip[32];
        char mac[32];
        printf("strlen(buf) = %d\n",strlen(buf));//29
        ExtractIpMac(buf,ip,mac);
        printf("buf=%s ip=%s mac=%s\n",buf,ip,mac);
//buf=192.168.1.2|00:11:22:33:44:55 ip=192.168.1.2 mac=00:11:22:33:44:55
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值