c - 如何在C中的引号之间找到子字符串

标签 c string

如果我有一个字符串比如是命令的字符串

echo 'foobar'|cat

有什么好的方法可以让我获取引号(“foobar”)之间的文本吗?我读到可以使用 scanf 在文件中执行此操作,是否也可以在内存中执行?

我的尝试:

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

最佳答案

使用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;
}

输出:

the thing in between quotes is 'foobar'


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

关于c - 如何在C中的引号之间找到子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36827579/

相关文章:

c - Linux 操作系统 - 来自父进程、子进程、父进程的输入输出管道

c - 相当于 c 中的 rm –rf

c - 为什么这会打印 10 颗星?

c - scanf 后变量重置

javascript - 包含小数的国际 pretty-print 字符串对象

java - 当改变对话视角时,如何可靠地将 "you"替换为 "me"或 "I"?

Swift - 删除重复的标点符号

c - 使用 C 的基本文件输入

c - 一种计算 __VA_ARGS__ 参数数量(包括 0)的方法,无需编译器特定的构造

java - 在特定字符串位置添加字符