如何在C中查找引号之间的子字符串

Nik*_*ntz 4 c string

如果我有一个字符串,例如命令的字符串

回声'foobar'|猫

有没有一种好方法可以让我获得引号之间的文本(“foobar”)?我读到可以scanf在文件中执行此操作,是否也可以在内存中执行此操作?

我的尝试:

  char * concat2 = concat(cmd, token);
  printf("concat:%s\n", concat2);
  int res = scanf(in, " '%[^']'", concat2);
  printf("result:%s\n", in);
Run Code Online (Sandbox Code Playgroud)

gsa*_*ras 5

使用strtok()一次,找到您想要的分隔符的第一次出现('在您的情况下),然后再次使用,找到它的结尾对,如下所示:

#include <stdio.h>
#include <string.h>

int main(void) {
  const char* lineConst = "echo 'foobar'|cat"; // the "input string"
  char line[256];  // where we will put a copy of the input
  char *subString; // the "result"

  strcpy(line, lineConst);

  subString = strtok(line, "'"); // find the first double quote
  subString=strtok(NULL, "'");   // find the second double quote

  if(!subString)
    printf("Not found\n");
  else
    printf("the thing in between quotes is '%s'\n", subString);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

引号之间的内容是 'foobar'


我是基于这个:How to extract a substring from a string in C?