考虑到 C 中的“”,使用分隔符拆分字符串
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 = '[=10=]';
}
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);
}
}
我如何编写一个函数来夹住一个以
作为分隔符的字符串,但考虑到 "
中的某些内容必须被视为一件事:
示例:
输入:
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 = '[=10=]';
}
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);
}
}