Ejemplo n.º 1
0
/*
 * Given a string, split it at any of the provided separators to form a
 * vector, destructively modifying the string to nul-terminate each segment.
 * If the third argument isn't NULL, reuse that vector; otherwise, allocate a
 * new one.  Any number of consecutive separators are considered a single
 * separator.
 */
struct cvector *
cvector_split_multi(char *string, const char *seps, struct cvector *vector)
{
    char *p, *start;
    size_t i, count;

    vector = cvector_reuse(vector);

    count = split_multi_count(string, seps);
    if (vector->allocated < count)
        cvector_resize(vector, count);

    for (start = string, p = string, i = 0; *p != '\0'; p++)
        if (strchr(seps, *p) != NULL) {
            if (start != p) {
                *p = '\0';
                vector->strings[i++] = start;
            }
            start = p + 1;
        }
    if (start != p)
        vector->strings[i++] = start;
    vector->count = i;

    return vector;
}
Ejemplo n.º 2
0
/*
 * Given a string, split it at any of the provided separators to form a
 * vector, copying each string segment.  If the third argument isn't NULL,
 * reuse that vector; otherwise, allocate a new one.  Any number of
 * consecutive separators are considered a single separator.  Returns NULL on
 * memory allocation failure, after which the provided vector may only have
 * partial results.
 */
struct vector *
strength_vector_split_multi(const char *string, const char *seps,
                        struct vector *vector)
{
    const char *p, *start;
    size_t i, count;
    bool created = false;

    /* Set up the vector we'll use to store the results. */
    if (vector == NULL)
        created = true;
    vector = strength_vector_reuse(vector);
    if (vector == NULL)
        return NULL;

    /* Count how big a vector we need and resize accordingly. */
    count = split_multi_count(string, seps);
    if (count == 0)
        return vector;
    if (vector->allocated < count && !strength_vector_resize(vector, count))
        goto fail;

    /* Now, walk the string and build the components. */
    vector->count = 0;
    for (start = string, p = string, i = 0; *p != '\0'; p++)
        if (strchr(seps, *p) != NULL) {
            if (start != p) {
                vector->strings[i] = strndup(start, (size_t) (p - start));
                if (vector->strings[i] == NULL)
                    goto fail;
                i++;
                vector->count++;
            }
            start = p + 1;
        }

    /* If there is anything left in the string, we have one more component. */
    if (start != p) {
        vector->strings[i] = strndup(start, (size_t) (p - start));
        if (vector->strings[i] == NULL)
            goto fail;
        vector->count++;
    }
    return vector;

fail:
    if (created)
        strength_vector_free(vector);
    return NULL;
}