[英]split string with delimiters taking into account ' " ' in C
我如何编写一个夹板字符串的函数
作为分隔符,但考虑到"
中的某些内容必须被视为一件事:
例子:
输入 :
char *input = "./display \"hello world\" hello everyone";
char **output = split(input);
输出 :
output[0] = ./display
output[1] = hello world
output[2] = hello
output[3] = everyone
output[4] = NULL
我不会保证这一点,也不会在没有更多思考和一些测试的情况下运行它,因为无疑会遗漏一些边缘情况,但一个快速而肮脏的解决方案可能看起来像:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct string_array {
char **data;
size_t cap;
size_t len;
};
void
append(struct string_array *v, char *s)
{
while( v->cap <= v->len ){
v->cap += 128;
v->data = realloc(v->data, v->cap * sizeof *v->data);
if( v->data == NULL ){
perror("malloc");
exit(EXIT_FAILURE);
}
}
v->data[v->len++] = s;
}
char **
split(char *input)
{
struct string_array v = {NULL, 0, 0};
char *t = input;
while( *t ){
int q = *t == '"';
char *e = q + t + strcspn(t + q, q ? "\"" : " \"\t\n");
append(&v, t + q);
t = (*e == '"') + e + strspn(e + (*e == '"'), " \"\t\n");
*e = '\0';
}
append(&v, NULL);
return v.data;
}
int
main(int argc, char **argv)
{
char *input = strdup(argc > 1 ? argv[1] :
"./display \"hello world\" hello everyone");
char **output = split(input);
for( char **t = output; *t; t += 1 ){
printf("%ld: '%s'\n", t - output, *t);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.