tags:

views:

71

answers:

2

I'm trying to parse the string below in a good way so I can get the sub-string stringI-wantToGet:

const char *str = "Hello \"FOO stringI-wantToGet BAR some other extra text";

str will vary in length but always same pattern - FOO and BAR

What I had in mind was something like:

const char *str = "Hello \"FOO stringI-wantToGet BAR some other extra text";

char *probe, *pointer;
probe = str;
while(probe != '\n'){
    if(probe = strstr(probe, "\"FOO")!=NULL) probe++;
    else probe = "";
    // Nulterm part
    if(pointer = strchr(probe, ' ')!=NULL) pointer = '\0';  
    // not sure here, I was planning to separate it with \0's
}

Any help will be appreciate it.

A: 

In first loop, scan until to find your first delimiter string. Set an anchor pointer there.

if found, from the anchor ptr, in a second loop, scan until you find your 2nd delimiter string or you encounter end of the string

If not at end of string, copy characters between the anchor ptr and the 2nd ptr (plus adjustments for spaces, etc that you need)

sizzzzlerz
+3  A: 

I had some time on my hands, so there you are.

#include <string.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

int getStringBetweenDelimiters(const char* string, const char* leftDelimiter, const char* rightDelimiter, char** out)
{
    // find the left delimiter and use it as the beginning of the substring
    const char* beginning = strstr(string, leftDelimiter);
    if(beginning == NULL)
        return 1; // left delimiter not found

    // find the right delimiter
    const char* end = strstr(string, rightDelimiter);
    if(end == NULL)
        return 2; // right delimiter not found

    // offset the beginning by the length of the left delimiter, so beginning points _after_ the left delimiter
    beginning += strlen(leftDelimiter);

    // get the length of the substring
    ptrdiff_t segmentLength = end - beginning;

    // allocate memory and copy the substring there
    *out = malloc(segmentLength + 1);
    strncpy(*out, beginning, segmentLength);
    (*out)[segmentLength] = 0;
    return 0; // success!
}

int main()
{
    char* output;
    if(getStringBetweenDelimiters("foo FOO bar baz quaz I want this string BAR baz", "FOO", "BAR", &output) == 0)
    {
        printf("'%s' was between 'FOO' and 'BAR'\n", output);
        // Don't forget to free() 'out'!
        free(output);
    }
}
zneak
+1 - Teach someone to fish, or hand them a talking fish that teaches them how to fish.
Tim Post
Thanks a lot! much more than what I was looking for.
Josh