簡體   English   中英

在沒有strtok / lexer的情況下將字符串解析為標記

[英]parsing a string into tokens without strtok/lexer

我想將字符串解析為令牌數組。 '\\ 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,將\\\\分隔的令牌啟動並推送到數組中。

計算機科學發生了什么?

無論如何都要寫FSA- http://en.wikipedia.org/wiki/Finite-state_machine

可以用桌子做

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM