【问题标题】:string parsing and substring in cc中的字符串解析和子字符串
【发布时间】:2010-04-25 15:19:18
【问题描述】:

我正在尝试以一种好的方式解析下面的字符串,以便获得子字符串stringI-wantToGet:

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

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
}

任何帮助将不胜感激。

【问题讨论】:

  • 为什么 str 不包含 '\n'? C 字符串以 NULL 结尾,因此您可能应该探测 0(或 NULL)。
  • 首先,告诉我们运行这段代码时会发生什么。
  • 感谢大家的建议!很棒的信息!

标签: c string parsing


【解决方案1】:

我有一些时间,所以你来了。

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

【讨论】:

  • +1 - 教别人钓鱼,或者给他们一条会说话的鱼,教他们如何钓鱼。
  • 非常感谢!比我想要的要多得多。
【解决方案2】:

在第一个循环中,扫描直到找到您的第一个分隔符字符串。在那里设置一个锚指针。

如果找到,则从锚点 ptr 在第二个循环中扫描,直到找到第二个分隔符字符串或遇到字符串结尾

如果不在字符串末尾,则在锚点 ptr 和第二个 ptr 之间复制字符(加上您需要的空格等调整)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 2010-11-07
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 2015-03-23
    • 2022-11-17
    相关资源
    最近更新 更多