gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:24 24 4
gpt4 key购买 nike

我正在尝试以一种好的方式解析下面的字符串,以便我可以获得子字符串 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
}

任何帮助将不胜感激。

最佳答案

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

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

关于c - c中的字符串解析和子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2708719/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com