Open wutiejun opened 7 years ago
#include <stdio.h> #include <stdlib.h> #include <string.h> // // split the string into sub-string by flag // int string_split(char * pRawStr, char flag, char * pResult[], int max_itme) { int sub_num = 0; char * pStr = pRawStr; pResult[sub_num++] = pStr; while (*pStr != '\0') { pStr++; if (*pStr == flag) { *pStr = '\0'; pStr ++; pResult[sub_num++] = pStr; if (sub_num >= max_itme) { return sub_num; } } } return sub_num; } #define MAX_PORT_NUM (256) #define MAX_SUB_STR (256) #define MAX_SUB_RANG_STR (4) int CheckNumberSelected(const char *pRawStr, unsigned char PortMap[], int MaxMap) { int Strlen = strlen(pRawStr) + 1; char * TempStr = malloc(Strlen); char *pSubstring[MAX_SUB_STR] = {0}; //assert TempStr != null memcpy(TempStr, pRawStr, Strlen); // int i; int MaxPort = 0; int substr = string_split(TempStr, ',', pSubstring, MAX_SUB_STR); for (i = 0; i < substr; i++) { char * pSub[MAX_SUB_RANG_STR] = {0}; int sub2 = string_split(pSubstring[i], '-', pSub, MAX_SUB_RANG_STR); if (sub2 == 2) { int start = atoi(pSub[0]); int end = atoi(pSub[1]); while (start <= end) { //assert start < MaxMap PortMap[start] = 1; MaxPort = start; start++; }; } else { int port = atoi(pSub[0]); //assert port < MaxMap PortMap[port] = 1; MaxPort = port; } } return MaxPort; } int main(int argc, char * argv[]) { const char * pRawString = "1,2,3-10,11,19,20-22,30-40,43,50"; if (argc >= 2) { pRawString = argv[1]; } unsigned char SelectedPortMap[MAX_PORT_NUM] = {0}; int MaxPort = CheckNumberSelected(pRawString, SelectedPortMap, MAX_PORT_NUM); MaxPort = MaxPort; // warning //assert MaxPort < MAX_PORT_NUM printf("Selected ports:\r\n"); int i; for (i = 0; i < MAX_PORT_NUM; i ++) { if (SelectedPortMap[i] == 1) { printf("%d ", i); } } puts("\r\n"); //getchar(); return 0; }