C/C++ 简单拆分字符串使用函数包括strstr, strcspn, strrchr

strstr, strcspn, strrchr函数的简单应用 

待拆分字符串: http://www.xxx.com|http://www.yyy.com:88

拆分结果:

    http://www.xxx.com:0

    http://www.yyy.com:88

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <list>
#include <conio.h>
#include <time.h>
#include <algorithm>
#include <windows.h>
#include <string>
#include <string.h>

//#pragma comment(lib,"ws2_32.lib")

using namespace std;

int iNum = 0;
char uip[100][32];
u_short DProt[100];

void TragetToIpAndProt(char *ip)
{

	char ipTemp[64] = {"0"};
	char chip[32] = {"0"},chprot[32] = {"0"};
	char *ptr = NULL,*ptr2 = NULL;

	while(*ip)
	{
		if (strstr(ip,"|") != NULL)  //如果找到分隔符说明多个目标
		{
			//strstr会返回'|'首次出现的地址,这里也可以用len=strstr(ip,"|")-ip
			int len = strcspn(ip,"|");
			//cout << len << endl << strstr(ip,"|")-ip << endl;
			strncpy(ipTemp,ip,len);    //分解出其中一个IP

			//有端口,由于http:多个冒号,所以判断我们要分隔的位置大于4
			//srrrchr返回指定字符最后一次出现的地址
			if ((ptr = strrchr(ipTemp,':')) != NULL && (ptr - ipTemp) > 4)  
			{
				strncpy(chip,ipTemp,ptr-ipTemp);
				ptr += 1;
				strcpy(chprot,ptr);
				strcpy(uip[iNum],chip);
				DProt[iNum] = atoi(chprot);  
			}else
			{
				strcpy(uip[iNum],ipTemp);
				DProt[iNum] = 0;
			}
			ip += strlen(ipTemp) + 1;
		}else//最后一个目标了
		{
			strcpy(ipTemp,ip);
			if ((ptr2 = strrchr(ipTemp,':')) != NULL && (ptr2 - ipTemp) != 4)
			{
				strncpy(chip,ipTemp,ptr2-ipTemp);
				ptr2 += 1;
				strcpy(chprot,ptr2);
				strcpy(uip[iNum],chip);
				DProt[iNum] = atoi(chprot);      
			}else
			{
				strcpy(uip[iNum],ipTemp);
				DProt[iNum] = 0;    
			}
			ip += strlen(ipTemp);
		}


		memset(ipTemp,0,sizeof(ipTemp));
		memset(chip,0,sizeof(chip));
		memset(chprot,0,sizeof(chprot));
		iNum++;
	}

}

int main(int argc, char* argv[])
{
	char *str = "http://www.xxx.com|http://www.yyy.com:88";
	TragetToIpAndProt(str);

	printf("%s:%d\n%s:%d\n", uip[0], DProt[0], uip[1], DProt[1]);
	printf("%s\n", str);
	
	system("pause");
	return 0;
}
执行结果

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任飘萍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值