我想将一个字符串解析为一个标记数组。 '\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 分隔的标记压入数组。
最佳答案
关于c - 在没有 strtok/lexer 的情况下将字符串解析为标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23459954/