【发布时间】:2017-03-13 09:38:37
【问题描述】:
我正在编写一个函数,它应该读取一串数字,用逗号分隔。字符串格式如下:
"1, 2, 3"
唯一的“规则”是函数可以容忍任何空格或制表符,只要每个数字之间有 一个 逗号。
如果字符串有效,则将数字存储在链表中。
例如,以下字符串是有效的:
"1,2,14,2,80"
" 250 , 1, 88"
但以下内容无效:
" 5, 1, 3 ,"
"51, 60, 5,,9"
我首先用 strtok() 试试运气(使用分隔符“,\t”,但据我目前的理解,不可能检查错误。所以我编写了自己的函数,但我非常不开心有了它 - 我认为代码很糟糕,虽然它似乎可以工作,但我真的很想知道是否有一种更清洁、更简单的方法来实现这样的功能。
我的功能是:
void sliceNumbers(char * string)
{
/*flag which marks if we're expecting a comma or not*/
int comma = FALSE;
/*Are we inside a number?*/
int nFlag = TRUE;
/*error flag*/
int error = FALSE;
/*pointer to string start*/
char * pStart = string;
/*pointer to string end*/
char * pEnd = pStart;
/*if received string is null*/
if (!string)
{
/*add error and exit function*/
printf("You must specify numbers");
return;
}
/*this loop checks if all characters in the string are legal*/
while (*pStart != '\0')
{
if ((isdigit(*pStart)) || (*pStart == ',') || (*pStart == ' ') || (*pStart == '\t'))
{
pStart++;
}
else
{
char tmp[2];
tmp[0] = *pStart;
tmp[1] = 0;
printf("Invalid character");
error = TRUE;
pStart++;
}
}
if (!error)
{
pStart = string;
if (*pStart == ',')
{
printf("Cannot start data list with a comma");
return;
}
pEnd = pStart;
while (*pEnd != '\0')
{
if (comma)
{
if (*pEnd == ',')
{
if (!nFlag)
{
}
if (*(pEnd + 1) == '\0')
{
printf("Too many commas");
return;
}
*pEnd = '\0';
/*Add the number to the linked list*/
addNumber(pStart, line, DC);
comma = FALSE;
nFlag = FALSE;
pStart = pEnd;
pStart++;
pEnd = pStart;
}
else if (isdigit(*pEnd))
{
if (!nFlag)
{
printf("numbers must be seperated by commas");
pEnd++;
}
else
{
if (*(pEnd + 1) == '\0')
{
pEnd++;
/*Add the number to the linked list*/
addNumber(pStart);
comma = FALSE;
nFlag = FALSE;
pStart = pEnd;
pStart++;
pEnd = pStart;
}
else
{
pEnd++;
}
}
}
else if (*pEnd == '\0')
{
if (nFlag)
{
/*Add the number to the linked list*/
addNumber(pStart, line, DC);
}
else
{
printf("Too many commas");
}
}
else if (*pEnd == ' ' || *pEnd == '\t')
{
nFlag = FALSE;
pEnd++;
}
}
else
{
if (*pEnd == ',')
{
printf("There must be only 1 comma between numbers");
return;
}
else if (isdigit(*pEnd))
{
if (*(pEnd + 1) == '\0')
{
pEnd++;
/*Add the number to the linked list*/
addnumber(pStart, line, DC);
comma = FALSE;
nFlag = FALSE;
pStart = pEnd;
pStart++;
pEnd = pStart;
}
else
{
pStart = pEnd;
pEnd++;
nFlag = TRUE;
comma = TRUE;
}
}
else if (*pEnd == ' ' || *pEnd == '\t')
{
if (!nFlag)
{
pEnd++;
}
else
{
pEnd++;
}
}
}
}
}
}
【问题讨论】:
-
看看strsep
-
您告诉我们如果输入有效,程序应该做什么,但不告诉我们如果输入无效怎么办。我可以想到可以为您设置此问题的两种方式:“您的程序必须检测到无效输入并报告错误”或“输入保证有效,因此您的程序不需要处理它”。这会影响我们的回答。
-
检查
strtok的返回值判断一行是否有效应该没有问题。如果返回的令牌长度为零,否则无效,通过在令牌上执行atoi()添加到数组。 -
构造状态机。你有 ~3 种令牌类型和 ~5 种状态。
标签: c string algorithm error-handling comma