// TorrentDataParse.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include <string.h>
#include <string>
bool IsValidInt(char * pData, int & nNum)
{
char * pTemp = pData;
int nState = 0;
char c = 0;
char buf[256] = { 0 };
if (!pData)
return false;
while (*pTemp)
{
c = *pTemp;
switch (nState)
{
case 0:
{
if (c != 'i')
return false;
nState = 1;
break;
}
case 1:
{
if ((c == '+') || (c == '-') || ((c >= '1') && (c <= '9')))
{
nState = 2;
break;
}
return false;
}
case 2:
{
if ((c >= '0') && (c <= '9'))
{
break;
}
if (c == 'e')
{
nState = 3;
break;
}
return false;
}
case 3:
{
if(c)
return false;
}
}
pTemp++;
}
for (int i = 1; i < strlen(pData) - 1; i++)
{
buf[i - 1] = pData[i];
}
nNum = atol(buf);
return true;
}
bool IsValidString(char * pData, std::string & strVal)
{
int nPos = -1;
int i = -1;
char Num[128] = { 0 };
char Str[256] = { 0 };
int nNum = 0;
for (i = 0; i < strlen(pData); i++)
{
if (pData[i] == ':')
{
nPos = i;
break;
}
}
if (nPos == -1)
return false;
for (i = 0; i < nPos; i++)
{
if (isdigit(pData[i]) == false)
return false;
Num[i] = pData[i];
}
nNum = atol(Num);
for (i = nPos + 1; i < strlen(pData); i++)
{
Str[i - nPos - 1] = pData[i];
}
if (strlen(Str) != nNum)
return false;
strVal = Str;
return true;
}
int main()
{
std::string str;
if (IsValidString("4:jimo", str))
{
printf("%s\n", str.c_str());
}
else
{
printf("invalid string\n");
}
if (IsValidString("4:jimo5", str))
{
printf("%s\n", str.c_str());
}
else
{
printf("invalid string\n");
}
if (IsValidString(":jimo5", str))
{
printf("%s\n", str.c_str());
}
else
{
printf("invalid string\n");
}
if (IsValidString("r4:jimo5", str))
{
printf("%s\n", str.c_str());
}
else
{
printf("invalid string\n");
}
system("pause");
return 0;
}
运行效果如下: