简体   繁体   English

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

[英]string parsing and substring in c

I'm trying to parse the string below in a good way so I can get the sub-string stringI-wantToGet : 我正在尝试以一种很好的方式解析下面的字符串,以便可以获取子字符串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 str长度会有所不同,但始终是相同的模式-FOO和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. 任何帮助将不胜感激。

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);
    }
}

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 如果找到,请在第二个循环中从锚点ptr进行扫描,直到找到第二个定界符字符串,或者遇到该字符串的结尾

If not at end of string, copy characters between the anchor ptr and the 2nd ptr (plus adjustments for spaces, etc that you need) 如果不在字符串末尾,则在定位点ptr和第二个ptr之间复制字符(加上所需的空格调整等)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM