【问题标题】:Reading a string of numbers separated by commas读取以逗号分隔的一串数字
【发布时间】: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


【解决方案1】:

您已经定义了许多布尔值(尽管您已将它们声明为ints)来跟踪当前状态。您可以将这些组合成一个state 变量,使用#define 定义可能的值:

#define STATE_START 0
#define STATE_IN_NUMBER 1
#define STATE_COMMA 2
#define STATE_FINISHED 3
#define STATE_ERROR 4

int state = STATE_START;

您可以绘制一个图表(有点像流程图),显示每个角色如何将我们从一种状态转移到另一种状态。

(对于我的图像,我保持简单,只显示输入的非错误状态,没有空格)

或者简单地说:

current state   | input     | next state| side effect
-----------------------------------------------------------------------
START           | digit     | IN_NUMBER | start storing a number
START           | other     | ERROR     | 
IN_NUMBER       | digit     | IN_NUMBER | continue storing a number
IN_NUMBER       | comma     | COMMA     | complete storing a number
IN_NUMBER       | null      | FINISHED  | finalise output
IN_NUMBER       | other     | ERROR     | report error
COMMA           | digit     | IN_NUMBER | start storing a number
COMMA           | comma     | ERROR     |
COMMA           | other     | ERROR     |

(对于我的表格,我添加了基本的错误状态,但仍然没有考虑空格)

您将需要添加更多状态和转换来处理空格和制表符,但原则不会改变。我建议从一个没有空格的实现开始,然后添加它。

这允许您编写一个有限状态机,其实现如下所示:

int state = STATE_START;
while(state != STATE_FINISHED && state != STATE_ERROR) {
    char c = input[offset++];
    switch(state) {
        case STATE_START:
            state = handleStateStart(...);
            break;
        case STATE_IN_NUMBER:
            state = handleInNumber(...);
            break;
        // etc.
        default:
            sprintf(error_message, "Reached unsupported state: %c", state);
            state = STATE_ERROR;
    }
}

处理函数的参数需要传入它将读取和修改的数据结构。例如:

int handleStateStart(
    char c,
    int* current_number,
    char *error_message) 
{
    if( ! isDigit(c)) {
        sprintf(error_message, "Expected a digit at char %d", *offset);
        return STATE_ERROR;
    }
    *current_number = atoi(c);
    return STATE_IN_NUMBER;
}

(这是一种易于理解的状态机实现方式,但还有其他方式可以做到:Is there a typical state machine implementation pattern?

您的 CSV 解析问题非常适合状态机,生成的代码将非常整洁。状态机用于更复杂的解析任务,并大量用于编译器等。稍后在您的学习中,您会遇到正则表达式——正式而言,正则表达式是一种紧凑的方式来表达消耗字符的有限状态机。

【讨论】:

  • 您可能还需要处理空格。我认为:1, 2 3, 4, 5 不应被视为有效字符串。
  • @joop "你需要添加更多的状态和转换来处理空格和制表符,但原则不会改变"
  • 你可以通过传递一个包含所有工作数据的结构来简化handleStateStart()——但我决定不假设结构的知识。
  • 另外请注意我使用了sprintf。在实际代码中使用snprintf
【解决方案2】:

strtok() 是这样做的正确方法。但仅将","(逗号)作为分隔符传递。您可以检查结果字符串的长度是否为零 (strlen(tok)==0),这意味着您有两个连续的 ','。检查后,您只需修剪结果,即。 e.如here所述。

【讨论】:

  • From 'man strtok' 解析字符串中两个或多个连续分隔符的序列被认为是单个分隔符。字符串开头或结尾的分隔符将被忽略。换句话说:strtok() 返回的标记总是非空字符串。
  • 我认为这是一道作业题,所以目的是写一个算法,而不是使用库函数。
  • @slim 那么为什么 OP 会提到strtok(),然后说他/她唯一的问题是因为错误检查?不要认为 OP 对他的“算法” 使用库函数有问题。
  • @dmuir 感谢您的提示。但是,检查第一个字符应该没什么大不了的。
  • @AminNegm-Awad 我的意思是 OP 说连续的分隔符是一个错误,你无法使用 strtok 检测到这一点
【解决方案3】:

您可以使用正则表达式库

1) 验证字符串

[^\d, ]|,[[:blank:]]+,|,{2,}

其中
[^\d, ] - 找到除数字、逗号和空格之外的所有符号
,[[:blank:]]+,|,{2,} - 验证字符串 2 个或多个逗号,其中空格和制表符在逗号之间没有数字

2) 进程号

\d+

您可以在线试用here

【讨论】:

    【解决方案4】:

    一种非常有效的直接方法:

    1. 一次性删除所有空格和制表符。您可以通过就地操作来避免空间开销。
    2. 读取数字流并继续将它们添加到链接列表中。如果检测到任何无效数字(例如长度为 0),只需返回一个 NULL 指针,然后停止进一步处理。
    3. 如果 pass 2 成功完成,则返回该链表的头指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2016-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多