gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:21:34 25 4
gpt4 key购买 nike

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

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/

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