我正在寻找一种非常简单的方法来返回包含在尾随字符串和前导字符串之间的字符串数组。这是一个例子:
char *text = ;;;Text I want]]] Text I don't care about ;;;More Text I want]]] More text I don't care about
调用 stringBetweenString(";;;","]]]",text)
应返回一个数组 (const char *myArray[2]
),其内容如下值:“我想要的文本”,“我想要更多文本”
。
不幸的是,我无法访问此应用程序的 RegEx,也无法访问外部库。任何帮助将不胜感激,谢谢!
最佳答案
不需要正则表达式
,正如其他人指出的那样,strstr
将在字符串中搜索子字符串的出现,返回指向子字符串开头的指针成功时为子字符串,否则为 NULL。您可以使用简单的指针算术来解析子字符串之间所需的文本,例如:
#include <stdio.h>
#include <string.h>
#define MAXC 128
int main (void) {
char *text = ";;;Text I want]]] Text I don't care about ;;;More "
"Text I want]]] More text I don't care about";
char buf[MAXC] = "", *p = text, *ep;
while ((p = strstr (p, ";;;"))) {
if ((ep = strstr (p, "]]]"))) {
strncpy (buf, p + 3, ep - p - 3);
buf[ep - p - 3] = 0;
printf ("buf: '%s'\n", buf);
}
else
break;
p = ep;
}
return 0;
}
示例使用/输出
$ ./bin/splitbetween
buf: 'Text I want'
buf: 'More Text I want'
关于c - 在 C 中获取两个字符串之间的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533868/