c中的字符串解析和子字符串

1 c string parsing

我试图以一种好的方式解析下面的字符串,以便我可以得到子字符串stringI-wantToGet:

const char *str = "Hello \"FOO stringI-wantToGet BAR some other extra text";
Run Code Online (Sandbox Code Playgroud)

str 长度会有所不同,但总是相同的模式 - FOO和BAR

我的想法是这样的:

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
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将是欣赏它.

zne*_*eak 5

我有一些时间在我的手上,所以你就是.

#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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1 - 教别人钓鱼,或者给他们讲一条教他们如何钓鱼的会说话的鱼. (2认同)