【问题标题】:Parsing "combined" string input in C解析C中的“组合”字符串输入
【发布时间】:2020-12-06 10:51:05
【问题描述】:

需要一些关于您认为在 C 中解析特定输入的最佳方法的提示。

输入的格式为xx xx xx xx xx xx xx y1 y2 y3 y4,其中xxyy可以是从a到z的任意两个字符,但它们的含义不同。

xx 需要被视为“个人”并执行一些验证。 y0 需要被视为组合并具有不同的设置验证和操作。 (例如,需要同时验证 y1 和 y2,然后使用它们执行操作)。

我使用函数strtoken 来遍历xx 字符,因为它的分隔符是空格字符。但是对于第二部分,我需要更改该行为,因为代码需要知道 3 个连续的空格字符,这表明我们现在处于第二部分,并且需要开始验证 y 组合。

欢迎所有提示 :) 谢谢

【问题讨论】:

  • 您可以使用char *ptr = strstr(input, " "); 找到中断的位置。如果找到,请在该点写入字符串终止符'\0',并使用两个字符串inputptr+3
  • 我假设xxs 或yns 的数量没有固定值?比如,它们的数量是可变的?是否至少有一个上限?
  • 嗨@Chase,xx 的数量确实是恒定的,但y's 的数量却没有

标签: c parsing c-strings


【解决方案1】:

根据 OP 的问题,xx 中包含的值没有限制。

I.E. xx 可以包含从 0x00,0x00 到 0xFF,0xFF 的任何值

可以使用switch() 语句,但对值没有限制,需要 256*256 个大小写。

y0y1y2 计算也有类似的考虑。

鉴于上述情况,代码将以:

开头
#include <stdio.h>
#include <string.h>


// '7' gotten from the OPs example
#define NUM_XX 7   

int main( void )
{
    char xx[2];
    char dummy;
    
    for( size_t x = 0; x < NUM_XX; x++ )
    {
        xx[0] = getchar();
        xx[1] = getchar();
        dummy = getchar();
        
        // calculate index
        int index_xx = xx[0]*256 + xx[1];
        switch( index_xx )  
        // index_xx could be most any value from 0 to 256*256
        {
            case 0:
                ....
                break;
                
            ....
            
            case 256*256:
                ....
                break;
        }
        
        // consume the intervening spaces
        getchar();
        getchar();
        getchar();
        
        char y0[2];
        char y1[2];
        char y2[2];
        
        the `y#`s would be read/processed in a similar loop, exiting the loop on EOF

【讨论】:

    猜你喜欢
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多