Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find substring between quotation marks in C

Tags:

c

string

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);
like image 768
Niklas Rosencrantz Avatar asked Jan 07 '23 05:01

Niklas Rosencrantz


1 Answers

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?

like image 148
gsamaras Avatar answered Jan 17 '23 00:01

gsamaras