All pastes #825 Raw Edit

parser, rev 3

public c v1 · immutable
#825 ·published 2004-09-01 21:11 UTC
rendered paste body
/* Copyright (c) 2004 Donald Becker and Stephen Olesen */#include <string.h>#include <stdlib.h>#include <stdio.h>#include <ctype.h>#include "memwatch.h"int parse_string(char *string, char ***word, char ***part) {    char *args, *p;    char **locWord, **locPart;    int i, count = 0;    /* Verify we got an argument, and pointers */    if(!string || !word || !part) return 0;        /* Trim leading white space, and duplicate string */    while(*string && isspace(*string)) string++;    i = strlen(string);    p = string + i - 1;    while(p >= string && isspace(*p)) {        i--; p--;    }    args = (char *)strndup(string, i);    if(!args) return -1;    string = (char *)strndup(string, i);    if(!string) { free(args); return -1; }        /* Count words */    p = args;        while(*p) {        while(*p && !isspace(*p++));        while(*p && isspace(*p++));        count++;    }        /* Allocate return pointers, and since it's a dynamic array, null terminate it */    *part = (char **)calloc(count + 1, sizeof(char*));    if(!part) return -1;    *word = (char **)calloc(count + 1, sizeof(char*));    if(!word) { free(part); return -1; }    /* Set pointers */    i = 0; p = args;    locWord = *word; locPart = *part;    while(*p) {        locWord[i] = p;        locPart[i] = string + (p - args);        i++;        while(*p && !isspace(*p))            p++;        while(*p && isspace(*p))            *p++ = '\0';    }    return count;}void parse_free(char **word, char **part) {    free(word[0]);    free(word);    free(part[0]);    free(part);}int main(void) {    char **word, **part;    int i = 0, j;    char *string[] = { "hi there", "hey", "hi bob  ", "hi bob ", " testing this ", " testing this out", 0 };    while(string[i]) {        printf("'%s': %d\n", string[i], parse_string(string[i], &word, &part));        j = 0;        while(word[j]) {            printf("\tword: '%s'\n", word[j]);            j++;        }        j = 0;        while(part[j]) {            printf("\tpart: '%s'\n", part[j]);            j++;        }        parse_free(word, part);        i++;    }}