我对Python编码非常熟悉,但现在我必须用C来进行stringparsing
我的意见:
input=“命令1 arg1 args2 arg3;command2 args1 args2 arg3;cmd3 arg1 arg2 arg3”
我的Python解决方案: 在
input = "command1 args1 args2 arg3;command2 args1 args2 args3;command3 arg1 arg2 arg3"
compl = input.split(";")
tmplist =[]
tmpdict = {}
for line in compl:
spl = line.split()
tmplist.append(spl)
for l in tmplist:
first, rest = l[0], l[1:]
tmpdict[first] = ' '.join(rest)
print tmpdict
#The Output:
#{'command1': 'args1 args2 arg3', 'command2': 'args1 args2 args3', 'cmd3': 'arg1 arg2 arg3'}
预期输出:Dict,命令作为键,参数在值中作为字符串连接
到目前为止,我的C解决方案:
我想将命令和参数保存在如下结构中:
^{pr2}$我创建了一个struct char*数组来保存用“;”分隔的cmd+args:
struct ari{char*value[200];};
功能:
struct ari inputParser(char* string){
char delimiter[] = ";";
char *ptrsemi;
int i = 0;
struct ari sepcmds;
ptrsemi = strtok(string, delimiter);
while(ptrsemi != NULL) {
sepcmds.value[i] = ptrsemi;
ptrsemi = strtok(NULL, delimiter);
i++;
}
return sepcmds;
首先,我添加了一个帮助结构:
struct arraycmd {
struct cmdr lol[10];
};
struct arraycmd parseargs (struct ari z){
struct arraycmd result;
char * pch;
int i;
int j = 0;
for (i=0; i < 200;i++){
j = 0;
if (z.value[i] == NULL){
break;
}
pch = strtok(z.value[i]," ");
while(pch != NULL) {
if (j == 0){
result.lol[i].command = pch;
pch = strtok(NULL, " ");
j++;
} else {
result.lol[i].args[j]= pch;
pch = strtok(NULL, " ");
j++;
}
}
pch = strtok(NULL, " ");
}
return result;
我的输出函数如下所示:
void output(struct arraycmd b){
int i;
int j;
for(i=0; i<200;i++){
if (b.lol[i].command != NULL){
printf("Command %d: %s",i,b.lol[i].command);
}
for (j = 0; j < 200;j++){
if (b.lol[i].args[j] != NULL){
printf(" Arg %d = %s",j,b.lol[i].args[j]);
}
}
printf(" \n");
}
}
但它只产生垃圾(与python解决方案中的输入相同):
(命令1 arg1 arg2 arg3;命令2 arg1 arg2 arg3;命令3 arg1 arg2 arg3)
命令0:command1 Arg 0=command2 Arg 1=arg1 Arg 2=arg2 Arg 3=arg3 Arg 19=command2 Arg 21=arg1 Arg 22=arg2 Arg 23=arg3 Arg 39=command3 Arg 41=arg1 Arg 42=arg2 Arg 43=arg3 分段故障
所以我希望有人能帮我解决这个问题。在
用python编写C逻辑可能更容易。这更接近于C,您可以尝试将其音译为C。您可以使用
strncpy
来提取字符串并将其复制到结构中。在您的问题是,您依赖于结构中的指针初始化为NULL。在
它们只是随机值,因此SEGV。在
当结构只有10个命令和19个参数时,还将打印200个命令和200个参数。在
检查这个解决方案。用valgrind测试无泄漏。 但是我在free里面实现了打印,你可以自己实现free函数,你可以改进splitter函数来实现更好的解析。在
相关问题 更多 >
编程相关推荐