【发布时间】: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。 -
重点是你必须弄清楚如何做到这一点,而不仅仅是问别人。困惑有助于你学习。
-
请显示您尝试过的方法之一。