【问题标题】:parsing a string into tokens without strtok/lexer在没有 strtok/lexer 的情况下将字符串解析为标记
【发布时间】:2014-05-04 18:27:19
【问题描述】:

我想将一个字符串解析为一个令牌数组。 '\n' 和 ';'是分隔符,例如:

hello;hello
world

应转换为包含:{"hello","hello","world"} 的数组。

我尝试了许多不同的方法来做到这一点,但总是失败(因为它需要一个动态的 char 数组 * 我无法实现它)。

请注意,我不能使用 strtok 或词法分析器。

我该怎么做?有什么要点吗?

编辑:这是我尝试使用的方法之一,但出现分段错误(可能是我的代码中某处的内存访问问题):

#include <stdio.h>
#include <malloc.h>
#include <fcntl.h>
#include <string.h>

typedef struct { 
    int fd;
    char *path;
    int size;
    char *mem;
    struct stat st;
} file;

file *readfile(char *path) {
    file *a=malloc(sizeof(file));
    a->path=path;
    a->fd=open(a->path,O_RDONLY);
    if(a->fd<0) return 0;
    fstat(a->fd,&a->st);
    a->size=a->st.st_size;
    a->mem=malloc(a->size);
    read(a->fd,a->mem,a->size);
    return a;
}

void releasefile(file *a) {
    free(a->mem);
    close(a->fd);
    free(a);
}

char **parse(int *w,file *a) {
    int i,j=0;
    w=0;
    for(i=0;i<=a->size;i++) {
        if(a->mem[i]=='\n' || a->mem[i]==';') { a->mem[i]='\0'; j++; }
    }
    char **out=malloc(sizeof(char *)*j);
    for(i=0;i<=a->size;i++) {
       if(a->mem[i-1]!='\0') continue;
       out[*w]=malloc(strlen(a->mem+i)+1);
       memcpy(out[*w],a->mem+i,strlen(a->mem+i)+1);
       w++;
           return out;
}

int main(int argc,char **argv) {
    file *a=readfile(argv[1]);
    int *w=malloc(sizeof(int));
    char **tokens=parse(w,a);
    int i;
    for(i=0;i<=*w;i++) {
        puts(tokens[i]);
        }
        releasefile(a);

    // ATM no need to check for mem leaks :)

}

算法描述:读取文件,将 \0 放在您看到分隔符的位置,开始并将由 \0 分隔的标记推送到数组中。

【问题讨论】:

  • 1.为什么“我不能使用 x”? (即,你不知道如何,有人禁止你,或者什么?) 2. char * 有什么问题?如果你发布你得到的东西会很有用——即使它不起作用。
  • 手动操作,循环,+==,诸如此类。
  • 您可以解析字符串以确定令牌的数量,然后malloc 数组,或者只是从任意大小的数组开始,必要时realloc
  • 重点是你必须弄清楚如何做到这一点,而不仅仅是问别人。困惑有助于你学习。
  • 请显示您尝试过的方法之一。

标签: c string parsing gcc


【解决方案1】:

计算机科学发生了什么?

无论如何写一个 FSA - http://en.wikipedia.org/wiki/Finite-state_machine

可以使用表格来做到这一点

【讨论】:

  • ...使用一张桌子、一把椅子、一支铅笔和一些纸,也许还有一本教科书。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多