首页 文章

将字符串解析为没有strtok / lexer的标记

提问于
浏览
0

我想将一个字符串解析为一个标记数组 . '\ 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 回答

相关问题