The sscanf
answer is perfect, but not very flexible. I add this in case you want more flexibility to parse strings. You can do it with regular expressions and in your case would be something like:
Piece of code taken from https://gist.github.com/ianmackinnon/3294587
I have added some modification to extract the numbers to the variables
#include <stdio.h>
#include <string.h>
#include <regex.h>
#include <stdlib.h>
int main ()
{
// Define regexp and input
char * source = "dimension[\"string\",1080,720];";
char * regexString = "[a-z]+\\[\"([a-z]+)\",([0-9]+),([0-9]+)\\]";
size_t maxMatches = 3;
size_t maxGroups = 4;
// Variables we want to extract from the input
char* str;
int n1;
int n2;
regex_t regexCompiled;
regmatch_t groupArray[maxGroups];
unsigned int m;
char * cursor;
if (regcomp(®exCompiled, regexString, REG_EXTENDED))
{
printf("Could not compile regular expression.\n");
return 1;
};
m = 0;
cursor = source;
for (m = 0; m < maxMatches; m ++)
{
if (regexec(®exCompiled, cursor, maxGroups, groupArray, 0))
break; // No more matches
unsigned int g = 0;
unsigned int offset = 0;
for (g = 0; g < maxGroups; g++)
{
if (groupArray[g].rm_so == (size_t)-1)
break; // No more groups
if (g == 0)
offset = groupArray[g].rm_eo;
char cursorCopy[strlen(cursor) + 1];
strcpy(cursorCopy, cursor);
cursorCopy[groupArray[g].rm_eo] = 0;
printf("Match %u, Group %u: [%2u-%2u]: %s\n",
m, g, groupArray[g].rm_so, groupArray[g].rm_eo,
cursorCopy + groupArray[g].rm_so);
switch (g)
{
case 1:
// Copy to the string now that we know the length
str = malloc(strlen(cursor)+1);
strcpy(str,cursorCopy + groupArray[g].rm_so);
break;
case 2:
n1 = (int) strtol(cursorCopy + groupArray[g].rm_so, (char **)NULL, 10); //(cursorCopy + groupArray[g].rm_so,10);
break;
case 3:
n2 = (int) strtol(cursorCopy + groupArray[g].rm_so, (char **)NULL, 10); //(cursorCopy + groupArray[g].rm_so,10);
break;
}
}
cursor += offset;
}
regfree(®exCompiled);
printf("Matches in variables: %s - %d - %d \n",str,n1,n2);
return 0;
}
This for me prints
Match 0, Group 0: [ 0-28]: dimension["string",1080,720]
Match 0, Group 1: [11-17]: string
Match 0, Group 2: [19-23]: 1080
Match 0, Group 3: [24-27]: 720
Matches in variables: string - 1080 - 720