1
0
mirror of https://github.com/stedolan/jq.git synced 2024-05-11 05:55:39 +00:00

Add index strings by string; return string indexes

% jq '.[","]'
    "a,bc,def,ghij,klmno"
    [1,4,8,13]
    %
This commit is contained in:
Nicolas Williams
2013-12-02 12:16:38 -06:00
parent ae7a042876
commit cac14a531d
3 changed files with 23 additions and 0 deletions

20
jv.c
View File

@@ -621,6 +621,26 @@ not_this:
}
#endif /* HAVE_MEMMEM */
jv jv_string_indexes(jv j, jv k) {
assert(jv_get_kind(j) == JV_KIND_STRING);
assert(jv_get_kind(k) == JV_KIND_STRING);
const char *jstr = jv_string_value(j);
const char *idxstr = jv_string_value(k);
const char *p;
int jlen = jv_string_length_bytes(jv_copy(j));
int idxlen = jv_string_length_bytes(jv_copy(k));
jv a = jv_array();
p = jstr;
while ((p = memmem(p, (jstr + jlen) - p, idxstr, idxlen)) != NULL) {
a = jv_array_append(a, jv_number(p - jstr));
p += idxlen;
}
jv_free(j);
jv_free(k);
return a;
}
jv jv_string_split(jv j, jv sep) {
assert(jv_get_kind(j) == JV_KIND_STRING);
assert(jv_get_kind(sep) == JV_KIND_STRING);

1
jv.h
View File

@@ -83,6 +83,7 @@ int jv_string_length_bytes(jv);
int jv_string_length_codepoints(jv);
unsigned long jv_string_hash(jv);
const char* jv_string_value(jv);
jv jv_string_indexes(jv j, jv k);
jv jv_string_slice(jv j, int start, int end);
jv jv_string_concat(jv, jv);
jv jv_string_vfmt(const char*, va_list);

View File

@@ -73,6 +73,8 @@ jv jv_get(jv t, jv k) {
v = jv_invalid_with_msg(jv_string_fmt("Start and end indices of an string slice must be numbers"));
jv_free(t);
}
} else if (jv_get_kind(t) == JV_KIND_STRING && jv_get_kind(k) == JV_KIND_STRING) {
v = jv_string_indexes(t, k);
} else if (jv_get_kind(t) == JV_KIND_NULL &&
(jv_get_kind(k) == JV_KIND_STRING ||
jv_get_kind(k) == JV_KIND_NUMBER ||