If I have a string such as the string that is the command
echo 'foobar'|cat
Is there a good way for me to get the text between the quotation marks ("foobar")? I read that it was possible to use scanf
to do it in a file, is it also possible in-memory?
My attempt:
char * concat2 = concat(cmd, token);
printf("concat:%s\n", concat2);
int res = scanf(in, " '%[^']'", concat2);
printf("result:%s\n", in);
Use strtok() once, to locate the first occurrence of delimiter you wish ('
in your case), and then once more, to find the ending pair of it, like this:
#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;
}
Output:
the thing in between quotes is 'foobar'
I was based on this: How to extract a substring from a string in C?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With