strstr, strcspn, strrchr函数的简单应用
待拆分字符串: http://www.xxx.com|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;
}