點分十進位制表示的IP地址解析方法
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <string>
#include <iostream>
#include <cassert>
using namespace std;
const int maxHostLen = 10;
const int ipCount = 4;
//函式功能:給定元素個數,建立字串陣列
//引數:elementCount 陣列元素個數
//引數:element 每個陣列元素的長度
//返回值:返回一個包含elementeredCount個長度為elementLen的字串陣列
char** mallocChar(int elementCount, int elementLen)
{
char** hostInfo = new char*[elementCount];
for (int i = 0; i < elementCount; i++)
{
hostInfo[i] = new char[elementLen];
memset(hostInfo[i], 0, sizeof(char)* elementLen);
}
return hostInfo;
}
//功能:動態分配記憶體字串陣列釋放
//引數:freeChar要釋放的字串陣列
//引數:elementCount 字串陣列元素個數
void freeChar(char** freeChar, int elementCount)
{
for (int i = 0; i < elementCount; i++)
{
if (freeChar[i])
{
delete freeChar[i];
freeChar[i] = NULL;
}
}
if (freeChar)
{
delete[] freeChar;
freeChar = NULL;
}
}
//功能:從給定的ip地址中解析點分字串
//引數:ipAddr要解析的ip地址
//引數:hostInfo 儲存解析結果
//返回值:解析成功返回TRUE,失敗返回False
bool findCstyle(char* ipAddr, char**& hostInfo)
{
int itertmp = 0;
char* tmp1 = ipAddr;
char* tmp2 = ipAddr;
while (*tmp1)
{
tmp1++;
if (*tmp1 == '.'|| *tmp1 == '\0')
{
strncpy(hostInfo[itertmp], tmp2, tmp1 - tmp2);
tmp2 = tmp1 + 1;
itertmp++;
}
}
if (hostInfo)
{
return true;
}
return false;
}
//功能:單一字串陣列
//引數:hostInfo要列印的字串陣列
//引數:element字串陣列中的元素個數
void print(char** hostInfo, int elementCount)
{
for (int i = 0; i < elementCount; i++)
{
printf("%s\n", hostInfo[i]);
}
}
void findCppStyle()
{
cout << "input your ip address:" << endl;
string address;
cin >> address;
string block1, block2, block3, block4;
int dot1 = address.find(".", 0);
assert(dot1 != string::npos);
block1 = address.substr(0, dot1);
//find函式的功能是從string中尋找指定字元,找到則返回該字元地址
int dot2 = address.find(".", dot1 + 1);
//string::npos表示到達字串的尾部
assert(dot2 != string::npos);
block2 = address.substr(dot1 + 1, dot2 - dot1 - 1);
int dot3 = address.find(".", dot2 + 1);
assert(dot3 != string::npos);
block3 = address.substr(dot2 + 1, dot3 - dot2 - 1);
assert(address.find(".", dot3 + 1) == string::npos);
block4 = address.substr(dot3 + 1, address.size() - dot3 - 1);
cout << block1 << endl;
cout << block2 << endl;
cout << block3 << endl;
cout << block4 << endl;
}
int main()
{
findCppStyle();
char ip[35] = { 0 };
printf("input your ip address:");
scanf("%s", ip);
char** hostInfo = mallocChar(ipCount, maxHostLen);
if (findCstyle(ip, hostInfo))
{
printf("output is :\n");
print(hostInfo, ipCount);
}
else
{
printf("fail\n");
}
freeChar(hostInfo, ipCount);
return 0;
}